I am witnessing a very weird behviour with the following Python code snippet.
list_of_dict = [{}]*2 # create a list of 2 dict
list_of_dict[0]["add_to_dict_0"] = 1 # add a (key,val) pair to 1st dict
print list_of_dict[0]
print list_of_dict[1]
The output is:
{'add_to_dict_0': 1}
{'add_to_dict_0': 1}
Both the dictionaries got updated, although I (explicitly) updated only one. However, changing the initialization in Line 1 to the following:
list_of_dict = [dict() for _ in xrange(0,2)]
fixes the issue.
What is the reason for this behaviour? I am guessing that this is an artefact of the concept of name-object binding in Python (as opposed to variable-memory location binding in other languages like C/C++). My guess is that in the first case, both list_of_dict[0]
and list_of_dict[1]
are bound to the same dictionary object.
Is my suspicion correct? If yes, then why is the behaviour not replicated in the second case? What is the difference between dict_object = dict()
and dict_object = {}
?