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.

Title: Assignment to list of lists gives incorrect result
Type: behavior Stage:
Components: Interpreter Core Versions: Python 2.5
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: loewis, stesteve
Priority: normal Keywords:

Created on 2008-06-10 04:24 by stesteve, last changed 2022-04-11 14:56 by admin. This issue is now closed.

File name Uploaded Description Edit stesteve, 2008-06-10 04:24 Simple case that shows the bug
Messages (2)
msg67894 - (view) Author: Steve Emmert (stesteve) Date: 2008-06-10 04:24
This bug is explained in the attached file.  The list of lists does not
behave correctly when it is defined by the makeGrid function in the
attached file.  When attempting to set the value of one element, it
actually sets multiple elements.  The same operation works differently
when the list of lists is defined with a literal.  I am using version
2.5.2 with Windows XP.  I am just learning Python, so I may have gotten
some terminology wrong.
msg67897 - (view) Author: Martin v. Löwis (loewis) * (Python committer) Date: 2008-06-10 04:57
This is not a bug. Please read about references in Python, and what this

py> b=[0]
py> a=[b,b]
py> a[0] is a[1]
py> c=[[0],[0]]
py> c[0] is c[1]
py> c[0] == c[1]

In short, there is only a single list stored in the variable gridRow,
and the very same list is appended multiple times (not copies of the
list, but the very same object). There are then multiple ways to refer
to the list, such as g[0] or g[1].

To avoid sharing the list objects, either create new lists (i.e. nest
the first loop into the second one, and create a new gridRow on each
outer loop iteration), or create clones of the first list, e.g.

# or
Date User Action Args
2022-04-11 14:56:35adminsetgithub: 47322
2008-06-10 04:57:09loewissetstatus: open -> closed
resolution: not a bug
messages: + msg67897
nosy: + loewis
2008-06-10 04:24:29stestevecreate