0

I was just playing around with python, take this code:

a=[[-1,-1,-1],[-1,-1,-1],[-1,-1,-1]]
b=[[-1]*3]*3
print(a)
print(b)
a[0][0]=6
b[0][0]=6
print(a)
print(b)

As I would expected it, both lists most be the same at the end, but they don´t, it looks like doing [[-1]*3]*3 creates by reference the lists, you can see that all first values from the list are change On console:

[[-1, -1, -1], [-1, -1, -1], [-1, -1, -1]]
[[-1, -1, -1], [-1, -1, -1], [-1, -1, -1]]
[[6, -1, -1], [-1, -1, -1], [-1, -1, -1]]
[[6, -1, -1], [6, -1, -1], [6, -1, -1]]

is it a bug or is it just a normal behaviour? I'm using python 3.7

John Balvin Arias
  • 2,632
  • 3
  • 26
  • 41

0 Answers0