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

iteration, list, name-binding, python

Solution

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]]

Problem

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?

Original source