2

I'm trying to do something with the python list of list but I found something weird about the indexing.
If I want to create a 2*2 "matrix", I do

matrix = [[0]*2]*2   

Then if I want to change the first row first column by using, say,

matrix[0][0] = 1    

I will get [[1,0],[1,0]], instead of [[1,0],[0,0]]. Does anyone know what went wrong?

John Kugelman
  • 330,190
  • 66
  • 504
  • 555
user129363
  • 21
  • 1

1 Answers1

6

Using the * operator on a list creates a shallow copy, so [[0]*2]*2 is equivalent to the following:

inner = [0, 0]
matrix = [inner, inner]

Because both locations in matrix are a reference to the same list, any modification to one will modify the other. Instead, use the following:

matrix = [[0]*2 for i in range(2)]
Andrew Clark
  • 192,132
  • 30
  • 260
  • 294