Python: Default list in function -
from summerfield's programming in python3:
it says follows: when default values given, created @ time def statement executed, not when function called. question following example:
def append_if_even(x, lst =none): lst = [] if lst none else lst if x % 2 ==0: lst.append(x) return lst
as first time definition executed, lst point none after function call append_if_even(2),
shouldn't lst point [2], since after lst.append(x) lst not point none anymore ?
why next execution still make lst point none?
- what happen inside function call append_if_even(2)?
shouldn't lst point [2], since after lst.append(x) lst not point none anymore? why next execution still make lst point none?
that prevent using lst=none
, lst = [] if lst none else lst
construction. while default arguments function evaluated once @ compile time, code within function evaluated each time function executed. each time execute function without passing value lst
, start default value of none
, replaced new empty list when first line of function executed.
if instead define function this:
def append_if_even(x, lst=[]): if x % 2 ==0: lst.append(x) return lst
then act describe. default value lst
same list (initially empty) every run of function, , each number passed function added 1 growing list.
for more information, see "least astonishment" , mutable default argument.
Comments
Post a Comment