Search code examples
pythonlistfunctionlocal-variables

Does a list defined in a functions parameter body acts as a static variable in python?


Here, the list is defined as a local variable in the parameter of the function foo, but I'm confused why even on repeated calls the list still remembers it's previous values, why is it acting like a static variable?

def foo(character,my_list = []):
    my_list.append(character)
    print(my_list)

foo("a")
foo('b')
foo('c')

---- Output ----

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

Solution

  • When you define a mutable value as default argument, what python does is something like this:

    default_list = []
    def foo(character, my_list=default_list):
        my_list.append(character)
    

    The same happens for any other mutable type (dict for instance). You can find a very detailed explanation here: https://docs.quantifiedcode.com/python-anti-patterns/correctness/mutable_default_value_as_argument.html

    One way you can make an empty list as a default for a list can be:

    def foo(character, my_list=None):
        if my_list is None:
            my_list = []
        my_list.append(character)