开发者

understanding for loops with reference to list containers in python

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开发者_StackOverflow社区. 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's

  1. Creating a new list object with three zeroes in it.
  2. Assigning a reference to the new list to a label called v

It doesn't matter if v was 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 the v = syntax. You must assign elements to it, like you mentioned, or use slice notation v[:] = as noted by Sven.


x = [[1,2,3],[4,5,6]]
for v in x:
    v[:] = [0,0,0]

should do the trick.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜