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: array assignment error
Type: behavior Stage: resolved
Components: Build Versions: Python 3.8
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: crazyguyx4, haowenqi.zz, veky, xtreak
Priority: normal Keywords:

Created on 2021-03-21 14:45 by haowenqi.zz, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (4)
msg389230 - (view) Author: Wen Hao (haowenqi.zz) Date: 2021-03-21 14:45
>>>mat = [[0]*4]*4
>>> mat
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> mat[1][2]=1
>>> mat
[[0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0]]
msg389233 - (view) Author: Vedran Čačić (veky) * Date: 2021-03-21 15:19
All three words in the title are wrong. :-D
msg389243 - (view) Author: Karthikeyan Singaravelan (xtreak) * (Python committer) Date: 2021-03-21 16:14
By using * 4 in the end you are making four lists having same reference. Hence change in one causes change in other 4 lists.

Relevant FAQ : https://docs.python.org/3/faq/programming.html#how-do-i-create-a-multidimensional-list
msg389245 - (view) Author: John Cena (crazyguyx4) Date: 2021-03-21 16:21
You are actually creating 4 references to the same list(See the ending *4). This is how python behaves. See the below link as well

https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly
History
Date User Action Args
2022-04-11 14:59:43adminsetgithub: 87747
2021-03-21 16:21:52crazyguyx4setnosy: + crazyguyx4
messages: + msg389245
2021-03-21 16:20:11rhettingersetstatus: open -> closed
resolution: not a bug
stage: resolved
2021-03-21 16:14:25xtreaksetnosy: + xtreak
messages: + msg389243
2021-03-21 15:19:37vekysetnosy: + veky
messages: + msg389233
2021-03-21 14:45:47haowenqi.zzcreate