0
Python code
Why is this code giving output [[1,0],[1,0]] instead of [[1,0],[0,0]] x = [[0]*2]*2 x[0][0]= 1 print(x)
4 odpowiedzi
+ 7
List of lists, so your dealing with list references so change in one list changes in the same reference list.
Gajendra Sonare
x = [0]*2
y = [x]*2 #equals to [x,x]
x[0]= 1 # all x refferences will effect x=[1, 0]
print(y) # [x,x]
+ 2
Your code is equivalent to this:
x = [[0,0]]
x = x + x
x[0][0] = 1
print(x)
I hope this makes it easier to understand what's going on ☺️
+ 2
Does this answer your question?
https://stackoverflow.com/questions/8822728/why-does-using-multiplication-operator-on-list-create-list-of-pointers
0
Let’s break it up step by step:
1) [[0]*2] is equal to [0, 0]
2) [0, 0] * 2 is equal to [[0, 0], [0, 0]]
3) Now regard your second line as (x[0])[0] which means the first index of the first list item: ([0, 0])[0].
Then you are replacing the first 0 with 1:
[[0, 0], [0, 0]] becomes [[1, 0], [0, 0]]
What if you try these instead of x[0][0] = 1:
for item in x:
item[0] = 1
print(x)
The whole code would be:
x = [[0]*2]*2
for item in x:
item[0] = 1
print(x)