For example,
def function(data=None):
print(data,id(data))
if data is None:
data=[]
print(data,id(data))
data.append(1)
print("==================")
function()
function()
>> None 1781798096
[] 1780266168520
==================
None 1781798096
[] 1780266174856
==================
At the first execution of function()
, variable data
refers to a "None" object(id:1781798096) By third line of the code, now data
refers to an empty list object(id:1780266168520) At second execution of function
, data
is expected to have the id value 1780266168520. But surprisingly, it gives out 1781798096 which is the same value when data
referred to the "None" object.
But if we change default parameter to some arbitrary list, say [0],
[0] 1780266149960
[0] 1780266149960
==================
[0, 1] 1780266149960
[0, 1] 1780266149960
==================
we find out that it gives identical id values.
So my question is why can't we modify a variable which previously referred to "None" object and why does such difference occur if we set default parameter to "None" and [0]?