Reputation: 264
I was wondering if someone could explain this to me:
In [400]: poz0=''
In [401]: poz1=''
In [402]: poz={0:poz0, 1:poz1}
In [403]: for i in range(1):
.....: poz[i]='some value '+str(i)
.....:
In [404]:
In [405]: poz[0]
Out[405]: 'some value 0'
In [406]: poz0
Out[406]: ''
I was expecting for poz0 to be == poz[0], same for poz1, but its not. Anyone could explain why?
Thanks
Upvotes: 1
Views: 160
Reputation: 9704
The values are different because str
instances are built-in immutable objects (numbers, strings, tuples, frozensets). So when you create the dictionary in poz={0:poz0, 1:poz1}
you are actually doing the same as poz={0:'', 1:''}
.
poz0
is not linked in any way with poz[0]
, there are different objects.
Update answering the comment:
With a list is not the same behaviour because lists are mutable objects:
In [9]: l = [1,2,3]
In [10]: d = {0: l}
In [12]: d[0]
Out[12]: [1, 2, 3]
In [13]: d[0].append(4)
In [14]: d[0]
Out[14]: [1, 2, 3, 4]
In [15]: l
Out[15]: [1, 2, 3, 4]
Upvotes: 2
Reputation: 363767
You reassigned poz[0]
to a different object, namely the value of 'some value '+str(0)
. The assignment operator =
does not modify poz[0]
's value but changing the binding in the dict
.
Upvotes: 4