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: List created by multiplication behaves different
Type: behavior Stage: resolved
Components: Versions: Python 3.1, Python 3.2, Python 3.3, Python 2.7, Python 2.6
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: r.david.murray, sandro.tosi, xintx-ua
Priority: normal Keywords:

Created on 2011-07-20 16:38 by xintx-ua, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (4)
msg140753 - (view) Author: Сергій Загорія (xintx-ua) Date: 2011-07-20 16:38
Next code:

def ill(row):
  row[1]=1
list_manual=[[0,0,0],[0,0,0],[0,0,0]]
list_generated=[[0,0,0]]*3
ill(list_manual[1])
print(list_manual)
ill(list_generated[1])
print(list_generated)

Will output:

[[0, 0, 0], [0, 1, 0], [0, 0, 0]]
[[0, 1, 0], [0, 1, 0], [0, 1, 0]]

Is it a bug?
msg140754 - (view) Author: Sandro Tosi (sandro.tosi) * (Python committer) Date: 2011-07-20 17:07
Hi,
no it's not a bug :)

What you actually get with [[0]]*3 is a list of 3 references to the same list, [0]:

>>> a = [[0], [0], [0]]
>>> b = [[0]]*3
>>> for i in a: print(id(i))
... 
139807725184032
139807725300280
139807725300520
>>> for i in b: print(id(i))
... 
139807725324016
139807725324016
139807725324016
msg140756 - (view) Author: Сергій Загорія (xintx-ua) Date: 2011-07-20 17:50
So the workaround is

for i in range(len(list_generated)):
  list_generated[i]=list(tuple(list_generated[i]))
msg140760 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2011-07-20 18:15
I'm not sure what your example is trying to achieve, but the list(tuple(...)) looks redundant.

Your initial example could be written:

  b = [[0] for i in range(3)]
History
Date User Action Args
2022-04-11 14:57:19adminsetgithub: 56806
2011-07-20 18:15:22r.david.murraysetnosy: + r.david.murray
messages: + msg140760
2011-07-20 17:50:57xintx-uasetmessages: + msg140756
2011-07-20 17:07:10sandro.tosisetstatus: open -> closed

nosy: + sandro.tosi
messages: + msg140754

resolution: not a bug
stage: resolved
2011-07-20 16:38:58xintx-uacreate