1

I need more clarification on how python handles the mutable objects when used in return statement.

def dict_return():
    d = {'a': "1234"}
    return d


d1 = dict_return()
print("d1 ID: ", id(d1))
d2 = dict_return()
print("d2 ID: ", id(d2))
print("Dict Return ID1: ", id(dict_return()))
print("Dict Return ID2: ", id(dict_return()))

I have above code sample the output is as below:

d1 ID:  6017792
d2 ID:  6018128
Dict Return ID1:  33645696
Dict Return ID2:  33645696

I'm using Python V3.6.3, as can be seen the last two lines have the same ID but when I assign the returned dict to variable, new variables are created. I want more clarification on why this happens if dict are mutable in Python.

Uday Swami
  • 395
  • 8
  • 22

0 Answers0