Because append
is a mutable operation, and when the code inside the function l.append(5)
is executed, it mutates the list l
, in second case, when you are l=[]
that's creation of an empty list, not the modification of the list passed.
Moreover, you can use id
to verify it
First approach
temp = [1, 2, 3]
def add_more(l):
print(f'id of l:{id(l)} before')
l.append(5)
print(f'id of l:{id(l)} after')
add_more(temp)
print(f'id of temp: {id(temp)}')
id of l:1605604079816 before
id of l:1605604079816 after
id of temp: 1605604079816
Second approach
temp = [1, 2, 3]
def add_more(l):
print(f'id of l:{id(l)} before')
l = []
print(f'id of l:{id(l)} after')
add_more(temp)
print(f'id of temp: {id(temp)}')
id of l:1605677713736 before
id of l:1605604079816 after
id of temp: 1605677713736
In the first approach id
, that is essentially the memory representation of a variable, is same for temp
and before and after inside the function.
But in second case, id
is same for temp
and before in the function, but not after because you are just creating an empty list and assigning it to l
, which is just a variable local inside the function.