Something in the function tutorial confused me.

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Mon Aug 6 03:12:02 EDT 2007


On Sun, 05 Aug 2007 23:50:24 -0700, Lee Fleming wrote:

> But this, the code that "fixes" the list accumulation confounds me:
> def  f(x, y=None):
>     if y is None: y = []
>     y.append(x)
>     return y
> 
> print f(23)  # prints [23]
> print f(42)  # prints [42]
> 
> Why didn't the second call to f, f(42) return [23, 42]?
> As I understand it, y is only None at the beginning of f(23).
> Then y changes from None to 23. When f ends, doesn't y still have 23
> in it, just as it did in the first function I discussed?

After the function's end, the name local name `y` doesn't exist anymore. 
If you enter a function, the names of the arguments with default values
are bound to those default values.  So in the second call `y` is bound to
`None` just like in the first example `y` is bound to the list at every
call.

> In other words, what's going on here? How is it that y accumulates
> argument values between function calls in the first function, but
> doesn't in the second one?

Not `y` is accumulating but the list object does.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list