Python: Default list in function

后端 未结 1 1002
粉色の甜心
粉色の甜心 2020-12-21 20:24

From the Summerfield\'s Programming in Python3:

it says as follows: when default values are given, they are created at the time the def statement is executed, not

相关标签:
1条回答
  • 2020-12-21 20:48

    Shouldn't 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=[]):
        if x % 2 ==0:
            lst.append(x)
        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.

    0 讨论(0)
提交回复
热议问题