Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested List and For Loop

Tags:

python

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

like image 311
Yugo Kamo Avatar asked Feb 04 '26 02:02

Yugo Kamo


1 Answers

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

like image 89
John La Rooy Avatar answered Feb 06 '26 15:02

John La Rooy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!