Something in the function tutorial confused me.
Stargaming
stargaming at gmail.com
Mon Aug 6 04:43:53 EDT 2007
On Sun, 05 Aug 2007 23:50:24 -0700, Lee Fleming wrote:
> Hello,
> I have a simple question. Say you have the following function:
>
> def f(x, y = []):
> y.append(x)
> return y
>
> print f(23) # prints [23]
> print f(42) # prints [23, 42]
>
> As far as I understand, the default value y, an empty list, is created
> when the def statement evaluates. With this thought in mind, the above
> calls
> to f make sense.
>
> 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? And if y has 23 in it,
> won't the second call to f not execute what's in the if statement?
>
> 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?
You're just unluckily shadowing the name `y` in the local scope of your
function. Your code snippet could be rewritten as::
def f(x, y=None):
if y is None: my_y = []
else: my_y = y
my_y.append(x)
return my_y
HTH,
Stargaming
More information about the Python-list
mailing list