0

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?

yuqli
  • 4,461
  • 8
  • 26
  • 46
  • Please take a look at this thread explaining how default values for function parameters work: https://stackoverflow.com/questions/13195989/default-values-for-function-parameters-in-python – cthulhu Mar 31 '18 at 20:33
  • Thanks @cthulhu for the pointer! Yes that seems to be what I need. – yuqli Mar 31 '18 at 20:41

0 Answers0