Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing matrix in Python using "[[0]*x]*y" creates linked rows?

Tags:

python

matrix

Initializing a matrix as so seems to link the rows so that when one row changes, they all change:

>>> grid = [[0]*5]*5
>>> grid
[[0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0]]
>>> grid[2][2] = 1
>>> grid
[[0, 0, 1, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 1, 0, 0]]

How can I avoid this?

like image 403
Zaz Avatar asked Mar 18 '26 15:03

Zaz


1 Answers

grid = [[0]*5 for i in range(5)]

Note: [int]*5 copies the int 5 times (but when you copy an int you just copy the value). [list]*5 copies the reference to the same list 5 times. (when you copy a list you copy the reference that points to the list in memory).

like image 94
robert king Avatar answered Mar 21 '26 04:03

robert king



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!