Nested list problem - please...

Chris Rebert clp2 at rebertia.com
Sat Apr 17 16:31:54 EDT 2010


On Sat, Apr 17, 2010 at 12:40 PM, Martin Hvidberg <Martin at hvidberg.net> wrote:
> I have this code, it builds up a data structure of nested lists, and filling data in them.
> My problem is that it seems that one of the lists SA[1] is not a list of unique instances but rather individual links to the same variable.
> In the example below I assign 'X' to what I intended to be the first Compounds Name. But rather the 'X' goes into all the Compounds Name.
> I thought that the [:] in SAdata.extend([CP[:]]) would ensure copies rather than links to.
> What is going wrong?

someList[:] only copies 1-level deep. If you have a list of lists,
none of the inner lists will be copied; you'll get a new list of
references to the same lists instead. I think your code assumes [:]
copies lists recursively.

Also, a.extend([b[:]]) is more efficiently and idiomatically written
as a.append(b[:])

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list