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: multiplying a list of dictionaries
Type: Stage: resolved
Components: Build Versions: Python 3.1, Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Andrew.Hays, benjamin.peterson, r.david.murray
Priority: normal Keywords:

Created on 2010-01-31 21:18 by Andrew.Hays, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (4)
msg98628 - (view) Author: Andrew Hays (Andrew.Hays) Date: 2010-01-31 21:18
[{}]*3 should produce a list of dictionaries that are 3 length long, which it does.  However, one would expect that if you assign something to the keyword 'abc' in the first dicitonary (e.g., x[0]['abc'] = 'def') that the other dictionaries would remain blank (e.g.,  x = [{'abc': 'def'}, {}, {}].  However, it appears that each dictionary is filled (e.g., x = [{'abc':'def'}, {'abc':'def'}, {'abc':'def'}]).

Creating a list of dictionaries like this [{}, {}, {}] or appending a dictionary to a list like this list.append({}) does NOT produce this same effect, it produces the desired effect.
msg98629 - (view) Author: Benjamin Peterson (benjamin.peterson) * (Python committer) Date: 2010-01-31 21:28
This is because multiply the list produces a reference to the same object 3 times.
msg98647 - (view) Author: Andrew Hays (Andrew.Hays) Date: 2010-02-01 03:59
Ah, my apolgogies, I didn't realize that.  I suppose I didn't look deeply enough into the situation.  I just realized that it worked that way with dictionaries, but by the same right, x=[[]]*3 would create [[], [], []] and if I said x[0][0]=1 then it would only do that for the first inner array. (e.g. x = [[1], [], []]).  Again, my apologies for not looking into this further.
msg98659 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2010-02-01 11:56
I'm not quite sure from what you wrote if you understood.  Just to make sure no one reading this ticket later gets confused: it works the same way for all objects, and the behavior that sometimes surprises people shows up with mutable objects.  So lists and dicts behave the same way in this scenario:

>>> x = [[]]*3
>>> x
[[], [], []]
>>> x[0].append(1)
>>> x
[[1], [1], [1]]
History
Date User Action Args
2022-04-11 14:56:57adminsetgithub: 52071
2010-02-01 11:57:01r.david.murraysetpriority: normal
stage: resolved
2010-02-01 11:56:33r.david.murraysetnosy: + r.david.murray
messages: + msg98659
2010-02-01 03:59:28Andrew.Hayssetmessages: + msg98647
2010-01-31 21:28:10benjamin.petersonsetstatus: open -> closed

nosy: + benjamin.peterson
messages: + msg98629

resolution: not a bug
2010-01-31 21:18:25Andrew.Hayscreate