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 2012-12-23 16:40 by christian.heimes. 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
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