Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 570
Martin Thoma Avatar asked Sep 18 '20 11:09

Martin Thoma


People also ask

Can you iterate over a tuple Python?

We can iterate over tuples using a simple for-loop. We can do common sequence operations on tuples like indexing, slicing, concatenation, multiplication, getting the min, max value and so on.

Is tuple faster than list Python?

Tuple is stored in a single block of memory. Creating a tuple is faster than creating a list. Creating a list is slower because two memory blocks need to be accessed. An element in a tuple cannot be removed or replaced.

What is an advantage of using a tuple over a list?

The advantages of tuples over the lists are as follows: Tuples are faster than lists. Tuples make the code safe from any accidental modification. If a data is needed in a program which is not supposed to be changed, then it is better to put it in 'tuples' than in 'list'.

What is the difference between a list and a tuple why would you use one over the other?

Tuples are typically used to store heterogeneous elements, which are elements belonging to different data types. Lists, on the other hand, are typically used to store homogenous elements, which are elements that belong to the same type.

What is the difference between list_NUM and tuple in Python?

Lists are surrounded by square brackets [] and Tuples are surrounded by parenthesis (). Above, we defined a variable called list_num which hold a list of numbers from 1 to 4 .The list is surrounded by brackets []. Also, we defined a variable tup_num; which contains a tuple of number from 1 to 4. The tuple is surrounded by parenthesis ().

Why we can't modify the tuple in Python?

We can't modify the tuple due to its immutable nature. Note: As the tuple is immutable these are fixed in size and list are variable in size. Lists has more builtin function than that of tuple. We can use dir ( [object]) inbuilt function to get all the associated functions for list and tuple.

How to iterate over a list in Python?

There are multiple ways to iterate over a list in Python. Let’s see all the different ways to iterate over a list in Python, and performance comparison between them. Method #1: Using For loop. Python3. list = [1, 3, 5, 7, 9] for i in list: print(i) Output: 1 3 5 7 9.

Do tuples use more memory than lists in Python?

As you can see from the output of the above code snippet, the memory required for the identical list and tuple objects is different. When it comes to the time efficiency, again tuples have a slight advantage over the lists especially when lookup to a value is considered. Well, obviously this depends on your needs.


1 Answers

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.

like image 62
MisterMiyagi Avatar answered Nov 14 '22 04:11

MisterMiyagi