Python: Default list in function

不想你离开。 提交于 2019-11-30 09:44:33

问题


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 when the function is called. But my question is for the following example:

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

As the first time definition executed, lst is point to None But after the function call append_if_even(2),

  • 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?

  • What really happen inside this function call append_if_even(2)?

回答1:


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.



来源:https://stackoverflow.com/questions/43255481/python-default-list-in-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!