Iterating in Python lists - does it copy or use iterator?

2.8k Views Asked by At

I have a list like this

a = [ [ 1,2,3 ], [ 4,5,6] ]

If I write

for x in a:
    do something with x

Is the first list from a copied into x? Or does python do that with an iterator without doing any extra copying?

3

There are 3 best solutions below

0
On

The for element in aList: does the following: it creates a label named element which refers to the first item of the list, then the second ... until it reaches the last. It does not copy the item in the list.

Writing x.append(5) will modify the item. Writing x = [4, 5, 6] will only rebind the x label to a new object, so it won't affect a.

1
On

Python does not copy an item from a into x. It simply refers to the first element of a as x. That means: when you modify x, you also modify the element of a.

Here's an example:

>>> a = [ [ 1,2,3 ], [ 4,5,6] ]
>>> for x in a:
...     x.append(5)
... 
>>> a
[[1, 2, 3, 5], [4, 5, 6, 5]]
1
On

First, those are mutable lists [1, 2, 3], not immutable tuples (1, 2, 3).

Second, the answer is that they are not copied but passed by reference. So with the case of the mutable lists, if you change a value of x in your example, a will be modified as well.