Simple del[] list question

Martijn Faassen m.faassen at vet.uu.nl
Wed Apr 26 14:07:44 EDT 2000


Matthew Hirsch <meh9 at cornell.edu> wrote:
[snip problem description]
> Why did a change?  Why suddenly when you go to two dimensions does the 
> behavior change?

It's because [:] only does a shallow copy; that is, it copies the list,
the individual elements are *not* copied; only new references are made.
So when you delete an element of a sublist, both lists will now have 
a reference to the same sublist which now misses an element.

Python is really very consistent about this, but tricky sometimes, indeed.

In order to make a deep copy of the list, use the deepcopy() function from
the standard copy module.

Note that another strategy which tends to avoid these troubles is to
construct a new list if you modify one. That is, usually if you're going
to alter some list, you're going to alter multiple elements, or perhaps
not include multiple elements, and not just a single one. In that case it's
easier and possibly even faster to do something like this:

mylist = [...] 
newlist = []
for element in mylist:
    if some_criterion(element):
        newlist.append(element)
mylist = newlist

By constructing a new list, you avoid the potential problems of some other
variable still pointing to your modified list.

Regards,

Martijn
-- 
History of the 20th Century: WW1, WW2, WW3?
No, WWW -- Could we be going in the right direction?



More information about the Python-list mailing list