0

Why the following code:

lst = [{}]*2
lst[0]['key'] = 7
print lst

gives [{'key':7}, {'key':7}]

Andy G
  • 19,232
  • 5
  • 47
  • 69
Tim
  • 355
  • 1
  • 8

3 Answers3

0

Your first line:

lst = [{}]*2

creates two identical dictionaries in your list (in reality it creates 2 references that both refer to the same dictionary object).

These dictionary references refer to the same object, so that when you change one, you also change the other.

With that in mind, you could have done the following to produce the same result

lst = [{}]*2
lst[1]['key'] = 7
print lst
sfletche
  • 47,248
  • 30
  • 103
  • 119
0
lst = [{}]*2

This gives not 2 dictionaries inside a list, but 2 references to the same dictionary. Thus changing "one" will change "the other" (well, they're the same thing hence the quotes).

list

     ___   ___
    |   | |   |
    | i0| | i1|
     ---   ---
      |     |
      |     |
   --        --
  |            |
   --->dict<---

(where i0 is index 0, and i1 is index 1)

Dair
  • 15,910
  • 9
  • 62
  • 107
0
lst = [{}]*2

This creates a list of dictionaries where both entries reference the same dictionary instance.

It's the same as

d = {}
lst = []
lst.append(d)
lst.append(d)
Martin Konecny
  • 57,827
  • 19
  • 139
  • 159