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?
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?
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.
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: