3

In the latest Python (3.2):

>>> l = [{}]*2
>>> l[1]['key'] = 'value'
>>> l
[{'key': 'value'}, {'key': 'value'}]

I expected l to be [{}, {'key': 'value'}] after this operation. Is it normal behaviour or a bug?

Dmitry Shachnev
  • 550
  • 6
  • 17
  • What you do means that `l[0] is l[1]` – Jochen Ritzel Aug 28 '11 at 11:11
  • 4
    After nearly 20 years of development, the answer to "Is [this] normal behaviour for python?" is pretty much always "yes". – Andrew Jaffe Aug 28 '11 at 11:15
  • To clarify Jochen's comment, if you type `l[0] is l[1]` you will get `True`, meaning they're the same object. – Tom Zych Aug 28 '11 at 11:19
  • 1
    @Dmitry Shachnev Study the data model (http://docs.python.org/reference/datamodel.html#objects-values-and-types) and the execution model (http://docs.python.org/reference/executionmodel.html#naming-and-binding) of Python – eyquem Aug 28 '11 at 13:17
  • @Dmitry Shachnev You may be interested by the answer I wrote in the following thread : (http://stackoverflow.com/questions/7203295/python-map-function-passing-by-reference-value/7204329#7204329) – eyquem Aug 28 '11 at 13:25

3 Answers3

12

Normal. Try using l = [{} for x in range(2)] instead.

[{}]*2 does not actually make 2 different dictionaries - it makes a list with two references to the same dictionary. Thus, updating that dictionary makes changes show up for both items in the list, because both items are actually the same dictionary, just referenced twice.

Amber
  • 507,862
  • 82
  • 626
  • 550
3

[{}]*2 doesn't result in a list with two dictionaries, it results in a list with the same dictionary twice. Use [{} for x in range(2)] instead.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

This code produces the same result over on Codepad for v 2.5.1

import sys

print sys.version_info 

l = [{}]*2
l[1]['key'] = 'value'
print l
Michael Easter
  • 23,733
  • 7
  • 76
  • 107