Yugo Kamo
Yugo Kamo

Reputation: 2389

Nested List and For Loop

Consider this:

list = 2*[2*[0]]
for y in range(0,2):
  for x in range(0,2):
    if x ==0:
      list[x][y]=1
    else:
      list[x][y]=2
print list

Result:

[[2,2],[2,2]]

Why doesn't the result be [[1,1],[2,2]]?

Upvotes: 3

Views: 1682

Answers (2)

marty
marty

Reputation: 21

Alternatively to save space:

>>> [[x,x] for x in xrange(1,3)]

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304127

Because you are creating a list that is two references to the same sublist

>>> L = 2*[2*[0]]
>>> id(L[0])
3078300332L
>>> id(L[1])
3078300332L

so changes to L[0] will affect L[1] because they are the same list

The usual way to do what you want would be

>>> L = [[0]*2 for x in range(2)]
>>> id(L[0])
3078302124L
>>> id(L[1])
3078302220L

notice that L[0] and L[1] are now distinct

Upvotes: 12

Related Questions