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 object variable assign with multiplication sign
Type: compile error Stage: resolved
Components: None Versions: Python 2.6
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: ezio.melotti, muzuiget
Priority: normal Keywords:

Created on 2010-06-28 21:34 by muzuiget, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (2)
msg108872 - (view) Author: muzuiget (muzuiget) Date: 2010-06-28 21:34
platform: ubuntu 10.04 amd64, python 2.6.5 r265:79063

run below code 

a = [{}, {}, {}]
b = [{}] + [{}] + [{}]
c = [{}] * 3
print a, len(a), type(a)
print b, len(b), type(b)
print c, len(c), type(c)
a[1]["test"] = 1234
b[1]["test"] = 1234
c[1]["test"] = 1234
print a
print b
print c

the output is 

[{}, {}, {}] 3 <type 'list'>
[{}, {}, {}] 3 <type 'list'>
[{}, {}, {}] 3 <type 'list'>
[{}, {'test': 1234}, {}]
[{}, {'test': 1234}, {}]
[{'test': 1234}, {'test': 1234}, {'test': 1234}]

each dict key in variable c seen to assign with the same value.
msg108873 - (view) Author: Ezio Melotti (ezio.melotti) * (Python committer) Date: 2010-06-28 21:40
That's because with [{}] * 3 you get a list with 3 copies of the same object, so all the elements in c refer to the same dict:
>>> a = [{}, {}, {}]
>>> b = [{}] + [{}] + [{}]
>>> c = [{}] * 3
>>> map(id, a)
[12850496, 12850784, 12850928]
>>> map(id, b)
[12851648, 12851072, 12851792]
>>> map(id, c)
[12852080, 12852080, 12852080]
History
Date User Action Args
2022-04-11 14:57:02adminsetgithub: 53354
2010-06-28 21:40:11ezio.melottisetstatus: open -> closed

nosy: + ezio.melotti
messages: + msg108873

resolution: not a bug
stage: resolved
2010-06-28 21:34:58muzuigetcreate