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

Scott David Daniels Scott.Daniels at Acm.Org
Sun May 2 16:04:03 EDT 2004


Rich Krauter wrote:

> On Sat, 2004-05-01 at 17:37, Porky Pig Jr wrote:
>>Anyway, the example is
>>def f(a, L=[]):
>>    L.append(a)
>>    return L
>>
>>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 
Here is the conceptual flaw:  We initialize f's default to None.
When we call f (with only a value for a), on entry to the function
we associate the name L with the default (None).  When the L = []
line is executed, we re-associate L with a new empty list.

In the original definition, we set the default to a particular new
empty list.  The default will remain that particular list.  L is a
name that is associated with objects, not a place a value is stored.

Mr. Pig, hopefully either my explanation or Mr. Krauter's (which is
also correct) will help you figure this out.  The difference between
the two is our guess at what you don't understand.  If it still does
not make sense, ask again.

An interesting exercise to show the bit about objects:

     a = []
     b = []
     print id(a), a, id(b), b
     a.append(1)
     print id(a), a, id(b), b
     a = b
     print id(a), a, id(b), b
     a.append(1)
     print id(a), a, id(b), b

If you can explain the output of the four print statements and are
still confused, my explanation is not on point.

-Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list