-2

Why does this happen?

In [1]: a=[[0]*2]*2
In [2]: a
Out[2]: [[0, 0], [0, 0]]
In [3]: a[0][0]=1
In [4]: a
Out[4]: [[1, 0], [1, 0]]

Shouldn't be?

In [4]: a
Out[4]: [[1, 0], [0, 0]]
alegasalv
  • 21
  • 4

1 Answers1

0

Create List of Single Item Repeated n Times in Python

As the link above explains, because you used the * operator, all the lists within your main list refer to the same list. So when you change one, you're really changing the others at the same time. Try this instead:

a = [[0, 0], [0, 0]]
a[0][0] = 1

That way you have explicitly defined two distinct sublists within a.

Jeff Moorhead
  • 181
  • 1
  • 15