1

When I manually declare and initialise all the elements in a list of lists and change one of the values, the change can be seen as one would expect.

a=[[0,0,0],[0,0,0]]
a[0][0]=9
print(a)

The output is [[9,0,0],[0,0,0]] as one would expect.

However, when I use shorthand notation, changing the first element of the first list changes the first element of all the lists. Here's the code:

a=[[0]*3]]*2
a[0][0]=9
print(a)

This time, the output is [[9,0,0],[9,0,0]]!

What's going on?

methi1999
  • 25
  • 6
  • This is expected behaviour when creating a list with shorthand, basically all the elements in this case share reference. – Ankit Jaiswal Jul 09 '18 at 14:43

0 Answers0