5

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?

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
smilitude
  • 265
  • 4
  • 9

3 Answers3

10

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]]
Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
  • 2
    To explicitly respond to "does Python do that with an iterator" the answer is yes, but a Python iterator isn't quite like a C++ iterator, and the fact that `x` is not a copy is separate -- if you were to do `x = a[1]` it also wouldn't make a copy. – agf Apr 07 '12 at 13:46
5

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.

Simon Bergot
  • 10,378
  • 7
  • 39
  • 55
4

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.

mVChr
  • 49,587
  • 11
  • 107
  • 104
  • It's not _exactly_ pass by reference, though that's close to what Python does. And be careful saying "change the value of x" because `x = 3` won't modify `a`. – agf Apr 07 '12 at 13:48