[Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept

Jeffrey Lim jfs.world at gmail.com
Wed Feb 9 22:56:01 CET 2005


On Wed, 9 Feb 2005 13:12:22 -0800, Mike Bell <ternary at gmail.com> wrote:
> The function's local variable L is not static, but "default argument
> value" is, which is what the documentation means when it says that it
> will evaluate these only once.  When the default value is a list (in
> your code, not "the empty list" but a list which happens to be empty
> when the default arguments are being evaluated), that same object is
> used every time the function is called.
> 

ah, thanks for the clarification! I more or less get it now (the key
was to think of everything in terms of object references).

Would you mind explaining to me in a bit more detail about how the
'==['a list']' operation works then? Frankly, the code and results i
get below nearly stumbled me...

>>> def f(a,L=[]):
...     if L==[5]:
...       print "'if L==[5]' caught - printing, and then resetting L..."
...       print L
...       L = []
...     L.append(a)
...     return L
...
>>> f(5)
[5]
>>> f(34)
'if L==[5]' caught - printing, and then resetting L...
[5]
[34]
>>> f('fjskl')
'if L==[5]' caught - printing, and then resetting L...
[5]
['fjskl']
>>>

My questions:
- is the '==' operation a 'list' comparison - rather than a pointer
comparison? (my experiments seem to indicate that it is a 'list'
comparison)
- if this is the case, then why does the 'if L==[5]' test still catch
later on, when the 'L' should no longer be a '[5]' list?
- if this is *not* the case then, then how do you determine the '=='
is supposed to match?
- or is this a matter of 'compare by value' first, then after we get a
match, we 'compare by reference' later on???

thanks for your time,
-jf


More information about the Tutor mailing list