Empty list as default parameter

Alex Panayotopoulos A.Panayotopoulos at sms.ed.ac.uk
Fri Nov 21 07:12:43 EST 2003


Hello all,

Maybe I'm being foolish, but I just don't understand why the following 
code behaves as it does:

     - = - = - = -

class listHolder:
    def __init__( self, myList=[] ):
        self.myList = myList

    def __repr__( self ): return str( self.myList )

# debug: 'a' should contain 42, 'b' should be empty. But no.
a = listHolder()
a.myList.append( 42 )
b = listHolder()
print a
print b

     - = - = - = -

I was expecting to see [42] then [], but instead I see [42] then [42]. It 
seems that a and b share a reference to the same list object. Why?

-- 
<<<Alexspudros Potatopoulos>>>
Defender of Spudkind





More information about the Python-list mailing list