0

If I define a default list parameter like so:

def foo(a, my_list=[]):
    my_list.append(a)
    return my_list

Then each successive call to foo() without passing the default parameter will append the element to this "hidden" list that seems to persist between calls.

print(foo('a'))
print(foo('b'))
print(foo('c'))

This prints:

['a']
['a', 'b']
['a', 'b', 'c']

Why is this happening? This seems like an antipattern. To avoid this, I have to add the following trick:

def foo(a, my_list=None):
    if my_list is None:
        my_list = []
    my_list.append(a)
    return my_list
Nick Weseman
  • 1,502
  • 3
  • 16
  • 22

1 Answers1

0

This actually happens because, functions are actually objects. take a look at this explanation it is very clear : http://effbot.org/zone/default-values.htm