Reputation: 7357
Consider the following:
>>> a = {}
>>> b = {}
>>> c = {}
>>> c['a'] = 'b'
>>> a
{}
>>> b
{}
>>> c
{'a': 'b'}
OK, this is all well and good. Exactly what I expect. So then I shorten it.
>>> a = b = c = {}
>>> c['a'] = 'b'
>>> a
{'a': 'b'}
>>> b
{'a': 'b'}
>>> c
{'a': 'b'}
What's going on? This doesn't happen with other immutable data types, like integers.
>>> a = b = c = 0
>>> a += 1
>>> a
1
>>> b
0
>>> c
0
I think it might have to do with immutability, but this behavior is very strange to me. Can anyone shed some light on why it happens?
Upvotes: 2
Views: 142
Reputation: 63739
You could try this:
a,b,c = [{}]*3 # <-- WRONG!
Edit:
a,b,c = ({} for i in range(3)) # <-- RIGHT!
Upvotes: 1
Reputation: 34698
Its the same as doing
a = []
b = a
b.append(1)
print a
When you type
a = {}
b = {}
c = {}
you are creating three seperate dicts,
a = b = c = {}
is one dict with three 'names'
Because ints (and other types) are immutable, they need new instances in memory. e.g. if you do
a = b = c = 0
b += 1
print id(b)
print id(c)
Upvotes: 1
Reputation: 12174
What's going on? This doesn't happen with other immutable data types, like integers.
You hit it on the head. Immutable data types (integers, strings etc) don't behave this way while mutable data types (lists, dictionaries etc) do.
When you do a = b = c = 0
all three names point to the same memory. As integers are immutable, when you change the value of one it has to create a new integer object in new memory while the others stay pointing to the old object. Mutable objects are modified in place, so all names still point to the same (modified) object.
Upvotes: 5