List Problem

Dave Angel d at davea.name
Sun Sep 23 18:03:32 EDT 2012


On 09/23/2012 05:44 PM, jimbo1qaz wrote:
> On Sunday, September 23, 2012 2:31:48 PM UTC-7, jimbo1qaz wrote:
>> I have a nested list. Whenever I make a copy of the list, changes in one affect the other, even when I use list(orig) or even copy the sublists one by one. I have to manually copy each cell over for it to work.
>>
>> Link to broken code: http://jimbopy.pastebay.net/1090401
> No, actually that's the OK code. http://jimbopy.pastebay.net/1090494 is the broken one.

I also would prefer an inline posting of the code, but if it's too big
to post here, it's probably too big for me to debug here.

The usual reason for such a symptom is a nested list, where you have
multiple references to the same inner list inside the outer.  When you
change one of those, you change all of them.

alist = [1, 2, 3]
blist = [alist, alist, alist]   #  or blist = alist * 3
print blist
alist.append(49)
print blist

davea at think:~/temppython$ python jimbo.py
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
[[1, 2, 3, 49], [1, 2, 3, 49], [1, 2, 3, 49]]

Solution to this is to make sure that only copies of alist get into
blist.  One way is

blist = [alist[:], alist[:], alist[:]]

More generally, you can get into this type of trouble whenever you have
non-immutable objects inside the list.

Understand, this is NOT a flaw in the language.  It's perfectly
reasonable to be able to do so, in fact essential in many cases, when
you want it to be the SAME item.


-- 

DaveA




More information about the Python-list mailing list