Something in the function tutorial confused me.
Alex Popescu
nospam.themindstorm at gmail.com
Mon Aug 6 07:13:45 EDT 2007
Stargaming <stargaming at gmail.com> wrote in news:46b6df49$0$26165
$9b622d9e at news.freenet.de:
> 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
For the given example this will continue to print:
> print f(23) # prints [23]
> print f(42) # prints [42]
so this doesn't solve/explain OP's initial question. A previous post has
already clarified the reasons for seeing this normal behavior.
bests,
./alex
--
.w( the_mindstorm )p.
More information about the Python-list
mailing list