newbie question on Python tutorial example in section 4.7.1 (default arg values)
Porky Pig Jr
porky_pig_jr at my-deja.com
Sat May 1 17:37:44 EDT 2004
Hello,
hope someone can clarify this section for me (or may be there is a
'newbie FAQs' in which case I would appreciate the link
Anyway, the example is
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.
Given this is how it works (?), I still don't understand how the
following workaround works:
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
well, it does work, but why? Seems like we initialize L to None (which
is as I undersatnd, sort of equivalent of C void), in fact it also
works if we initialize L to some arbitrary string. What I don't
understand: we check if
L is None, and then make it a list and append 'a' to it. So it becomes
a list. When then on the subsequent call it is None again rather than
list with a single value of 'a' (in the previous call)?
TIA
More information about the Python-list
mailing list