This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Pointer problem in initializing array of arrays
Type: Stage:
Components: None Versions: Python 2.6
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: mastermarv, pitrou
Priority: normal Keywords:

Created on 2010-09-29 08:40 by mastermarv, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (2)
msg117581 - (view) Author: Marvin Mundry (mastermarv) Date: 2010-09-29 08:40
>>> m1=[[0,0,0,0]]*4
>>> m1
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> m1[0][0]+=1
>>> m1
[[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]

after initializing an array of arrays as done in the first line of the code snippet all elements in the array point to the same object in memory.
msg117589 - (view) Author: Antoine Pitrou (pitrou) * (Python committer) Date: 2010-09-29 10:04
That's expected behaviour, syntactically. Multiplying a sequence doesn't deep-copy its elements.
If you want an array of distinct arrays, just write:

>>> m1 = [[0,0,0,0] for i in range(4)]
>>> m1[1][0] = 6
>>> m1
[[0, 0, 0, 0], [6, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
History
Date User Action Args
2022-04-11 14:57:07adminsetgithub: 54191
2010-09-29 10:04:06pitrousetstatus: open -> closed

nosy: + pitrou
messages: + msg117589

resolution: not a bug
2010-09-29 08:40:26mastermarvcreate