[Tutor] Python Lists

Hugo González Monteverde hugonz-lists at h-lab.net
Sat Jul 16 08:05:54 CEST 2005


Looks like you may be using default values in the constructor. The 
object is created with, say, an empty list as a default argument, but 
this argument is defined only one, when the function is defined.

look:

 >>> def myfunc(mylist = []):
     mylist.append(1)
     print mylist


 >>> myfunc()
[1]
 >>> myfunc()
[1, 1]
 >>> myfunc()
[1, 1, 1]
 >>>

all the calls use the same value, which originally was set to an empty 
list, but later it is no longer redefined.. this happens with all 
mutable types as default arguments.

It is likely this is our problem, check your constructors...

Hugo


DaSmith at technip.com wrote:
> 
> 
> 
> Hi, I am a new Python Programmer, and am encountering some problems with
> lists.
> 
> I have created a class which has many "Nested list" attributes. When I
> create a second instance of the class, the lists are not empty, and already
> contain the same values as were held in the previous instantiation. As a
> C/C++ programmer, this majes no semns to me at all. Could someone please
> explain to me what I must do to avoid this effect.
> 
> Kind Regards,
> 
> Daniel Smith. ( DaSmith at technip.com )
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


More information about the Tutor mailing list