classification
Title: Matrix operator star creates a false matrix
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 3.6, Python 3.5, Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: christian.heimes, xda@abalgo.com
Priority: normal Keywords:

Created on 2018-12-17 09:04 by xda@abalgo.com, last changed 2018-12-17 09:09 by christian.heimes. This issue is now closed.

Files
File name Uploaded Description Edit
python_bugreport.py xda@abalgo.com, 2018-12-17 09:04 Example that shows the bug
Messages (2)
msg331955 - (view) Author: Arnaud (xda@abalgo.com) * Date: 2018-12-17 09:04
It seems that the definition of a matrix like this:
a=[[0,0]]*4
does not create the matrix correctly by create 4 times the same pointer.
After the matrix creation, a
print(a)
gives the following result:
[[0, 0], [0, 0], [0, 0], [0, 0]]
which looks normal
print(type(a)) and print(type(a[1]) give also the correct result:
list

But when we try to change a matrix element:
a[2][0]=1
print(a)
gives a false result:
[[1, 0], [1, 0], [1, 0], [1, 0]]

When the matrix definition is done like this:
a=[[0, 0], [0, 0], [0, 0], [0, 0]]
the behavior is "as expected"
a[2][0]=1
print(a)
gives the correct result:
[[0, 0], [0, 0], [1, 0], [0, 0]]
msg331957 - (view) Author: Christian Heimes (christian.heimes) * (Python committer) Date: 2018-12-17 09:09
[[0,0]]*4 is not a matrix definition. You are defining a list that shares the same list object four times. It's a common misunderstanding how list works, see https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly
History
Date User Action Args
2018-12-17 09:09:23christian.heimessetstatus: open -> closed

nosy: + christian.heimes
messages: + msg331957

resolution: not a bug
stage: resolved
2018-12-17 09:04:28xda@abalgo.comcreate