简体   繁体   中英

Does it make a difference if you iterate over a list or a tuple in Python?

I'm currently trying the wemake-python-styleguide and found WPS335 :

Using lists, dicts, and sets do not make much sense. You can use tuples instead. Using comprehensions implicitly create a two level loops, that are hard to read and deal with.

It gives this example:

# Correct:
for person in ('Kim', 'Nick'):
    ...

# Wrong:
for person in ['Kim', 'Nick']:
    ...

Is this purely personal preference or is there more that speaks for using a tuple? I can only think about speed, but I cannot imagine that this makes a difference.

I think I have seen more people using lists and I wonder if there is a reason to change it.

Using lists instead of tuples as constants makes no difference in CPython. As of some versions, both are compiled to tuples.

>>> dis.dis("""
... for person in ["Kim", "Nick"]:
...     ...
... """)
  2           0 SETUP_LOOP              12 (to 14)
              2 LOAD_CONST               0 (('Kim', 'Nick'))
              4 GET_ITER
        >>    6 FOR_ITER                 4 (to 12)
              8 STORE_NAME               0 (person)

  3          10 JUMP_ABSOLUTE            6
        >>   12 POP_BLOCK
        >>   14 LOAD_CONST               1 (None)
             16 RETURN_VALUE

Note how the list literal was transformed to a LOAD_CONST (('Kim', 'Nick')) instruction of a tuple.


As for preference, CPython prefers tuple . If you have the choice, you should do so as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM