Empty list as default parameter

Thorsten Pferdekämper thorsten at pferdekaemper.com
Fri Nov 21 07:39:36 EST 2003


>
> 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?
>

Hi,
AFAIK, the default parameter values are only instantiated once. So, the
default-myList is always the same object. The coding above should be
rewritten like...

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

Regards,
    Thorsten








More information about the Python-list mailing list