3

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]]?

2 Answers 2

12

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

Sign up to request clarification or add additional context in comments.

2 Comments

yep! try list = [[0,0],[0,0]] instead.
Whoa. I was debugging this thing for a while, and it didn't seem to make sense. I added print statements, and it outputted the right values, but I didn't think that it would be like that!
0

Alternatively to save space:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.