Simple del[] list question
Gregoire Welraeds
greg at perceval.be
Thu Apr 27 04:07:06 EDT 2000
In reply to the message of Martijn Faassen sent on Apr 26 (see below) :
> 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
Isn't it time and memory consuming when working on big list (eg with 1000
or above elements) ?
--
Life is not fair
But the root password helps
--
Gregoire Welraeds
greg at perceval.be
Perceval Development team
-------------------------------------------------------------------------------
Perceval Technologies sa/nv Tel: +32-2-6409194
Rue Tenbosch, 9 Fax: +32-2-6403154
B-1000 Brussels general information: info at perceval.net
BELGIUM technical information: helpdesk at perceval.net
URL: http://www.perceval.be/
-------------------------------------------------------------------------------
On 26 Apr 2000, Martijn Faassen wrote:
> Date: 26 Apr 2000 18:07:44 GMT
> From: Martijn Faassen <m.faassen at vet.uu.nl>
> To: python-list at python.org
> Newsgroups: comp.lang.python
> Subject: Re: Simple del[] list question
>
> 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?
> --
> http://www.python.org/mailman/listinfo/python-list
>
>
More information about the Python-list
mailing list