2

Consider this

dict1={}
dict2={}
dict2["first_d2"]="Yes"
dict1["first_d1"]=dict2
print dict1
print dict2
dict2={}
print dict1      ===>Here's the doubt
print dict2

The Output:

{'first_d1': {'first_d2': 'Yes'}}
{'first_d2': 'Yes'}
{'first_d1': {'first_d2': 'Yes'}}   ===>Why is this not resetting?Its referencing to dict2
{}

Now python dictionaries are mutable.So dict1 is referencing to dict2.Now after first operation dict2 is reset,why is the value of dict1 not resetting?

As per my understanding mutable object change the contents in memory and do not return a new object.So why is this not happening here?What am i missing?

I am confused from the point of view of mutable and immutable!

vks
  • 67,027
  • 10
  • 91
  • 124
  • 1
    Already answered [here](http://stackoverflow.com/questions/369898/difference-between-dict-clear-and-assigning-in-python) and [here](http://stackoverflow.com/questions/30712256/programming-basic-python-assignment/30712592#30712592) – Markus Meskanen Jun 10 '15 at 08:50

1 Answers1

2
dict2 = {}

The above line only make the variable dict2 reference new variable, not the item in the dict1['first_d1'].

If you want to change both (clear all entries in dict2 dictionary), use dict.clear method:

dict2.clear()

In addition to this further info can be found here.

Community
  • 1
  • 1
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • @vks, `dict1['first_d1']` reference the dict object the `dict2` reference, not `dict2` variable itself. – falsetru Jun 10 '15 at 08:50
  • @vks, `dict2 = {}` does not change the object `dict2` reference, but make a new dictionary and make the variable `dict2` reference the new dictionary. – falsetru Jun 10 '15 at 08:57
  • @vks, Try to print the id of the dictionary object `id(dict2)` before and after `dict2 = {}` statement run. – falsetru Jun 10 '15 at 08:58
  • @vks, Any immutable / mutable object can be reassigned. `dict.clear()` method is there to mutate the dictionary. – falsetru Jun 10 '15 at 08:58
  • @vks, I hope this screenshot help delivering what I mean. http://i.imgur.com/gE6d2w9.png – falsetru Jun 10 '15 at 09:03
  • Just added a link which had more detailed answer.Hope u dont mind.Thanx a lot for answering my querries and `id` part did add to it. – vks Jun 10 '15 at 10:10