Python list vs tuple for on-the-fly iteration

Let's say I have components that I need to iterate over, such as From and To. For convenience, I can iterate over these lines, but I don't need them for a long period of time since I only need to do it once. Wouldn't it be better to use a list or a tuple in this case?

info = {}
for type in ('from', 'to'):
   info[type] = fetch(type);

      

Note that the above will work exactly the same if the tuple was changed to a list; I am wondering if there is any preference.

+3


source to share


5 answers


Unless you are going to change this, I think the tuple applies better. I only use lists when I need to do dynamic collection operations like append, subtract, etc.



Also, in most cases, access to the tuple is faster. That being said, you should always check your specific use case before making a decision.

+7


source


Tuples are most likely more efficient because they are immutable. Disassembly also shows that fewer opcodes are used with a tuple:

  2           0 SETUP_LOOP              14 (to 17)
              3 LOAD_CONST               3 (('a', 'b'))
              6 GET_ITER

      

against



  2           0 SETUP_LOOP              20 (to 23)
              3 LOAD_CONST               1 ('a')
              6 LOAD_CONST               2 ('b')
              9 BUILD_LIST               2
             12 GET_ITER

      

It doesn't really matter, if that bit of performance matters, you should write C or assembly code instead.

+7


source


Tuples seem to be smaller in memory and faster to create, but with 1 or 2 points, I have no idea how that matters in 99.99% of situations.

+1


source


Tuples are probably better than lists in this case, but you can also do

for item in a, b:
    process(item)

      

I am wondering what is actually going on in this case: P

Edit: this means:

3 LOAD_CONST               3 (('a', 'b'))

      

which appears to be a tuple ...

+1


source


If I understand your question correctly, you are asking what is the most idiomatic to use in this situation. (Performance and memory efficiency are almost irrelevant here, since you said you only do it once.)

The answer is that for most of Python's existence, people tend to use tuples for constant constants to iterate over, mainly due to the habit of using something immutable when there is no intent to mutate it.

[Edit: Got rid of some clumsy things about sets. I was too glad I helped him answer when it really didn't help.]

Note that sometimes there is a vocal minority who insist on the list. The rationale for this is that lists were originally conceived as an "array" type for Python, while tuples were a "record type". That is, lists were meant to hold multiple objects of the same type (such as a test suite), whereas tuples were meant to hold arbitrary related objects (such as name, address, and phone number). However, strict adherence to this is kind of archaic and bizarre.

+1


source







All Articles