[Tutor] strange listed nest behaviour

Dave S pythontut at pusspaws.net
Wed Jun 30 18:45:04 EDT 2004


I have a problem with lists,

As an example the following makes sense to me and works as I would 
expect ...

 >>> b=[[0,0,0,0],[0,0,0,0]]
 >>> b                      
[[0, 0, 0, 0], [0, 0, 0, 0]]
 >>> b[1][1]=5
 >>> b
[[0, 0, 0, 0], [0, 5, 0, 0]]
 >>>

However I have to set up a large data list, so I have used 
"self.startslot=[[float(0)]*110]*36" inside a class.
This is supposed to give me 0-35 lists each containing 0-109  floating 
point 0's which I can index into & change at will.
 
This dos not perform as expected and one write causes the same data to 
be written to multiple locations.

A more managable example being ...

 >>> a=[[float(0)]*10]*4
 >>> a
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 
0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]
 >>>
 >>> a[1][1]=5
 >>>
 >>> a
[[0.0, 5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 5, 0.0, 0.0, 
0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 
0.0, 0.0], [0.0, 5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]
 >>>

Printing 'a' gives the generated list as I would expect, but trying to 
write to one individual 'location' causes multiple 'locations' to be 
written to. (This caused me a headache before I twigged I can tell you :-) )

It must be something to do with the list definition but I am at a loss 
as to what is happening.

Can anyone tell me what I am doing wrong ?

Cheers
Dave







More information about the Tutor mailing list