Shah Vipul
Shah Vipul

Reputation: 747

python nested list value change not working

for i in range(len(arr)):
     temps = [[0]*9]*3   
# temp = [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 
0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]]

when tries

temps[0][0] = 4

gives this output

[[4, 0, 0, 0, 0, 0, 0, 0, 0], [4, 0, 0, 0, 0, 0, 0, 
0, 0], [4, 0, 0, 0, 0, 0, 0, 0, 0]]

tries to change the value of temp[0][0] it changes all temp[0][0] temp[0][1] temp[0][2] value

Upvotes: 0

Views: 93

Answers (1)

Jasmijn
Jasmijn

Reputation: 10452

Christian is right. [t] * 3 is equivalent to [t, t, t]

You can solve it by doing this:

for i in range(len(arr)):
     temps = [[0]*9 for _ in range(3)] 

Upvotes: 1

Related Questions