When I writing some Python codes using dict
, I found out the following behavior of my code:
In [1]: def foo(bar_dict):
...: print id(bar_dict)
...: bar_dict['new'] = 1
...: return bar_dict
...:
In [2]: old_dict = {'old':0}
In [3]: id(old_dict)
Out[3]: 4338137920
In [4]: new_dict = foo(old_dict)
4338137920
In [5]: new_dict
Out[5]: {'new': 1, 'old': 0}
In [6]: id(new_dict)
Out[6]: 4338137920
In [7]: old_dict
Out[7]: {'new': 1, 'old': 0}
In [8]: id(old_dict)
Out[8]: 4338137920
The old_dict
, new_dict
and the bar_dict
inside the foo
function are all point to on memory address. There is only one actually dict
object stored in the memory, even I pass a dict
inside a function.
I want to know more detail about this kind of memory management mechanism of Python, can anyone points me some good references explain about this? Also, when we use list
, set
or str
in Python, is there any similar behavior?