z=[0 for i in range(3)]
print(z) # [0,0,0]
x=[z for i in range(3)]
print(x) #[[0,0,0],[0,0,0],[0,0,0]]
x[1][1]=7
print(x) #[[0,7,0],[0,7,0],[0,7,0]]
Can someone explain what's happening here?
z=[0 for i in range(3)]
print(z) # [0,0,0]
x=[z for i in range(3)]
print(x) #[[0,0,0],[0,0,0],[0,0,0]]
x[1][1]=7
print(x) #[[0,7,0],[0,7,0],[0,7,0]]
Can someone explain what's happening here?
x=[z for i in range(3)]
In this line, it is the reference of z that is repeated as each element in the list x
So, when you modify one sub-list (or element of x
), all the other elements get modified as all are just references.