1

I am stumped by this silly and simple issue. Just can't understand what is wrong here!

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

i get the following output

[[0,0,0],[0,0,0]]
[[0,0,1],[0,0,1]]

I don't understand why I see two 1, while I changed only one of them. How do I change only one of them?

manav
  • 217
  • 1
  • 2
  • 11
  • What is your desired output? This can help? https://stackoverflow.com/questions/35166633/how-do-i-multiply-each-element-in-a-list-by-a-number – Super Mario May 09 '20 at 23:45

2 Answers2

2

by doing

a = [[0]*3]

You created an array

[0,0,0]

You then copied the reference to this array when you did

a = [[0]*3]*2

As a result changing one causes the other to change. This is known as a shallow copy.

What you want is a deepcopy and can be achieved by the copy's library deepcopy() method

Hence, do this instead:

 import copy
 a = [[0]*3]
 a += copy.deepcopy(a)
 a[1][2] = 1
 print(a)

[[0, 0, 0], [0, 0, 1]]

Jackson
  • 1,213
  • 1
  • 4
  • 14
0

It's because the [[0]*3]*2 is creating two smaller lists that are both associated to the same data value (because of the *2). To fix this, you would just want to define it in a different way that doesn't do this, for example:

a = [[0,0,0],[0,0,0]] or a = [[0]*3] + [[0]*3]

duckboycool
  • 2,425
  • 2
  • 8
  • 23