0

Why does this happen? Two methods that should give the same result but they don't:

a_good=[[0,0],[0,0]]
for i in [0,1]:
    for j in [0,1]:
        a_good[i][j]=str(i)+str(j) #[['00','01'],['10','11']]

a_error=[[0]*2]*2
for i in [0,1]:
    for j in [0,1]:
        a_error[i][j]=str(i)+str(j) #[['10','11'],['10','11']]  !?
Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40
Bernardo Costa
  • 441
  • 1
  • 11
  • 16

1 Answers1

1

In the second, a_error[0] and a_error[1] are references to the same list. So when you update the values stored in a_error[0] you are updating the values stored in a_error[1]

a_error=[[0]*2]*2
for i in [0,1]:
    print(a_error)
    for j in [0,1]:
        a_error[i][j]=str(i)+str(j) #[['10','11'],['10','11']]

print(a_error)


# [[0, 0], [0, 0]]
# [['00', '01'], ['00', '01']] # before i=1
# [['10', '11'], ['10', '11']] # after i=1
Russ Hyde
  • 2,154
  • 12
  • 21