I got this snippet of code from here:http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables
Its main idea is in Python, variables are name tags to objects. But then the author gives the following code, which I don't understand why they behave differently.
def bad_append(new_item, a_list = []):
a_list.append(new_item)
return a_list
bad_append(1) # returns [1]
bad_append(2) # returns [1, 2]
Another function:
def good_append(new_item, a_list = None):
if a_list == None:
a_list = []
a_list.append(new_item)
return a_list
good_append(1) # returns [1]
good_append(2) # returns [2]
This question might be relevant, but many concepts are mixed up (e.g mutable, reference, variables) and I'm still confused... How do I pass a variable by reference?
Thus, can I ask for some kind explanation on why the two functions above behave differently?