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: buggy assignment to items of a list created by a * operator
Type: Stage:
Components: Interpreter Core Versions: Python 3.3
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: christian.heimes, jenda.petrov@gmail.com
Priority: normal Keywords:

Created on 2012-12-23 16:33 by jenda.petrov@gmail.com, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (2)
msg177995 - (view) Author: jp (jenda.petrov@gmail.com) Date: 2012-12-23 16:33
The following code: 

li = [[1,0]]*5
a = [[1,10], [2,20], [3,30]]
for line in a:
    li[line[0]][0] = 2
print(li)

prints [[2,0],[2,0],[2,0],[2,0],[2,0]], but should print [[1,0],[2,0],[2,0],[2,0],[1,0]]. 

The output is correct if you, instead of using li = [[1,0]]*5, initialize the array as follows:

li = []
for i in range(5): li.append([1,0])
msg177996 - (view) Author: Christian Heimes (christian.heimes) * (Python committer) Date: 2012-12-23 16:40
The outcome is correct. You have fallen for a common beginners gotcha:

http://www.enricozini.org/2011/tips/python-list-gotcha
History
Date User Action Args
2022-04-11 14:57:39adminsetgithub: 60960
2012-12-23 16:40:18christian.heimessetstatus: open -> closed

nosy: + christian.heimes
messages: + msg177996

resolution: not a bug
2012-12-23 16:33:03jenda.petrov@gmail.comcreate