My question is regarding the following for loop:
x=[[1,2,3],[4,5,6]]
for v in x:
v=[0,0,0]
here if you print x you get [[1,2,3],[4,5,6]].. so the v changed is not really a reference to the list in x. But when you do something like the following:
x=[[1,2,3],[4,5,6]]
for v in x:
v[0]=0; v[1]=0; v[2] =0
then you get x as [[0,0,0],[0,0,0]]. This kinda gets difficult if the list inside x is quite long, and even doing something like this:
x=[[1,2,3],[4,5,6]]
for v in x:
for i in v:
i = 0
will give me x as [[1,2,3],[4,5,6]]. My best bet is to use for i in xrange(0,3): v[i]=0 .. Though I’d still like to know what’s going on here and what the other alternatives are when I have list of lists or more nested lists.
When python executes
v = [0, 0, 0], it’svIt doesn’t matter if
vwas a reference to something else before.If you want to change the contents of the list currently referenced by
v, then you can’t use thev =syntax. You must assign elements to it, like you mentioned, or use slice notationv[:] =as noted by Sven.