Re: Remove items from a list
From: Dan Perl (dperl_at_rogers.com)
Date: 09/08/04
- Next message: Carlos Ribeiro: "Re: A historical question"
- Previous message: Carlos Ribeiro: "Re: What about an EXPLICIT naming scheme for built-ins?"
- In reply to: Peter Otten: "Re: Remove items from a list"
- Next in thread: Peter Otten: "Re: Remove items from a list"
- Reply: Peter Otten: "Re: Remove items from a list"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Wed, 08 Sep 2004 17:29:16 GMT
Sorry, I missed that. And yes, that should be the problem. It's *A*
problem, for sure. Always a bad idea to modify the structure of a list
(deleting or inserting items) while iterating through it, but it's so easy
to forget that. Creating another list from the first one by filtering or
with a list comprehension should be the preferred solution, unless the
intention is to have this list used in more than one place and have the
changes reflected in all those places.
Dan
"Peter Otten" <__peter__@web.de> wrote in message
news:chnb4k$3qn$05$1@news.t-online.com...
> Dan Perl wrote:
>
> > But Stan says he tried something like that (see the comment in his code)
> > and
> > it was still not working. I would still need a more complete code
example
> > to reproduce the problem and figure out what went wrong.
>
> The following example might make it clearer:
>
> >>> files = "a.dbf b.dbf x.txt".split()
> >>> for index, fn in enumerate(files):
> ... print "checking", fn
> ... if fn.endswith(".dbf"):
> ... print "deleting", files[index]
> ... del files[index]
> ...
> checking a.dbf
> deleting a.dbf
> checking x.txt
> >>>
>
> The iterator operating on the files list keeps track of its current
position
> in the list by a simple index and is unaware of any changes to that list.
> If you delete an item _before_ or equal to that index position it will
> still be incremented on the next pass of the for loop, and therefore you
> never see item[n] that has become item[n-1] effectively by deleting one of
> its predecessors.
> To avoid this kind of trouble, Mel iterates over the list in reverse
order -
> deleting items _after_ the current position cannot confuse the iteration.
>
> Peter
>
- Next message: Carlos Ribeiro: "Re: A historical question"
- Previous message: Carlos Ribeiro: "Re: What about an EXPLICIT naming scheme for built-ins?"
- In reply to: Peter Otten: "Re: Remove items from a list"
- Next in thread: Peter Otten: "Re: Remove items from a list"
- Reply: Peter Otten: "Re: Remove items from a list"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|