Python: Default list in function

Python: Default list in function

Shouldnt lst point to [2], since after lst.append(x) lst not point to None anymore? Why the next execution still make lst point to none?

That is exactly what you prevent by using the lst=None, lst = [] if lst is None else lst construction. While the default arguments for the function are evaluated only once at compile time, the code within the function is evaluated each time the function is executed. So each time you execute the function without passing a value for lst, it will start with the default value of None and then immediately be replaced by a new empty list when the first line of the function is executed.

If you instead were to define the function like this:

def append_if_even(x, lst=None):
    if lst is None:
        lst = []
    if x % 2 == 0:
    return lst

Then it would act as you describe. The default value for lst will be the same list (initially empty) for every run of the function, and each even number passed to the function will be added to one growing list.

For more information, see Least Astonishment and the Mutable Default Argument.

Python: Default list in function

Leave a Reply

Your email address will not be published. Required fields are marked *