newbie answer on Python tutorial example in section 4.7.1 (default arg values)

Piet pit.grinja at gmx.de
Sun May 2 12:05:02 EDT 2004


porky_pig_jr at my-deja.com (Porky Pig Jr) wrote in message news:<56cfb0e3.0405011337.2a8710bc at posting.google.com>...
Hi TIA,
> def f(a, L=[]):
>     L.append(a)
>     return L
> 
> and somehow L just keeps growing between the calls, so
> 
> print f(1) 
> returns [1]
> and then
> print f(2)
> returns [1, 2]
> etc. I'm not really clear on this example, but assume that L is set
> aside somewhere (in the function definition), initialized only once
> (during the def), and then all subsequent calls affect that locally
> defined L.
I agree that this one is diffcult to get. The point is (or seems to
be) that when you do not provide a value for the second argument
(which is true for all the function calls), the default value is used.
So during the first call, the interpreter notices that L is lacking,
assigns the default value to it (empty list) and then passes this
parameter together with the already given 'a' to the function.
When you call the function a second time without a value for L, the
default L will again be passed to the function, but it will not be
evaluated, so the assignment "L = []" will not be executed and the
non-empty list L will be passed to the function.
When you change the function to
> def f(a, L=None):
>     if L is None:
>         L = []
>     L.append(a)
>     return L
your first function will evaluate the assignment for L resulting in
the "value" "None" for L (I am not sure whether one should talk about
values in this context). On successive calls to the function without a
given parameter for L, the expression for L will NOT be evaluated, but
the lack of the parameter will be noted, and thus the if-clause will
be evaluated as true and assign the value "[]" to L which will then be
used on further execution.
This is at least what I thought. I just checked the behaviour of the
function when you change the default value for L from "None" to "[]".
In this case I had expected that successive calls of the function
would notice the absence of L and that the if-clause would evaluate as
true as well, but this is not the case. So when you change the
function to
> def f(a, L=[]):
>     if L is None:
>         L = []
>     L.append(a)
>     return L
and write
f(1),f(2) and so on you will also see that the list is growing with
each function call.
So my post was not that helpful, I guess. Maybe a python expert has
some explanation. I am looking forward to see how that thread will
develop.
Best wishes
Piet



More information about the Python-list mailing list