-1

I just started doing Python, so this is pretty confusing for me.

This one prints 4

a = b = 4
a = 3
print b

However, this one prints {'a': 1}

d1 = d2 = {}
d1['a'] = 1
print d2

So why the discrepancy? I thought it had something to do with mutability, but aren't int also mutable?

Vishnu Upadhyay
  • 5,043
  • 1
  • 13
  • 24
C.J. Jackson
  • 152
  • 7

1 Answers1

1

Here a & b are immutable types. whilr dictionary are mutable types.

try id() function, it will tell you the exact story.

d1 = d2 = {}
print id(d1), id(d2)
d1['a'] = 1
print d2
print id(d1),'\n' ,id(d2)

#id(d1) :-140468952760680 
#id(d2):-140468952760680
#ID remian same.
a = b = 4
print id(a),'\n' ,id(b)

#id(a):- 12083536 
#id(b):- 12083536

a = 3
print b, id(a), id(b)

#id(a):-12083560 # it is changes
#id(b):-12083536

So when try to provide a different object (a=3) a new refrence is instantiated for the object.

Vishnu Upadhyay
  • 5,043
  • 1
  • 13
  • 24