I’m playing with for loops in Python and trying to get used to the way they handle variables.
Take the following piece for code:
a=[1,2,3,4,5]
b=a
b[0]=6
After doing this, the zeroth element of both b and a should be 6. The = sign points a reference at the array, yes?
Now, I take a for loop:
a=[1,2,3,4,5]
for i in a:
i=6
My expectation would be that every element of a is now 6, because I would imagine that i points to the elements in a rather than copying them; however, this doesn’t seem to be the case.
Clarification would be appreciated, thanks!
Everything in python is treated like a reference. What happens when you do
b[0] = 6is that you assign the6to an appropriate place defined by LHS of that expression.In the second example, you assign the references from the array to
i, so thatiis 1, then 2, then 3, … butinever is an element of the array. So when you assign 6 to it, you just change the thingirepresents.http://docs.python.org/reference/datamodel.html is an interesting read if you want to know more about the details.