Confused over Lists

Paul Brian paul1brian at yahoo.com
Fri Aug 2 10:48:24 EDT 2002


Thank you to you all. As usual amazed by the speed and usefulness of replies
on clp.
:-)


------------------------------
Paul Brian
(07899) 877 295
paul1brian at yahoo.com


"Jonathan Hogg" <jonathan at onegoodidea.com> wrote in message
news:B9705553.EFD5%jonathan at onegoodidea.com...
> On 2/8/2002 14:56, in article
> 1028296609.5721.0.nnrp-12.c1c3e11b at news.demon.co.uk, "Paul Brian"
> <paul1brian at yahoo.com> wrote:
>
> > the following I thought should work :-
> >
> > demoList = [1, 1, 2, 3, 4, 5]
> > for num in demoList:
> >   if num == 1:
> >       demoList.remove(num)
> > print demoList
> >
> > but I get
> >>>> [1, 2, 3, 4, 5]
> >
> >
> > There appears to be a magic counter that keeps track of what index it
has
> > already iteratered over in the list.
> > When the first "1" is encountered (index 0) it removes it, and shifts
the
> > next "1" to index 0.
> > But the magic counter thinks it has already visited index 0 and so
"blips"
> > over the second 1, thus not removing that "1" from the list.
>
> Modifying a list that you're looping over has undefined results. Better
> would be:
>
> >>> demoList = [1, 1, 2, 3, 4, 5]
> >>>
> >>> newList = [num for num in demoList if num <> 1]
> >>> newList
> [2, 3, 4, 5]
> >>>
>
> or:
>
> >>> newList = filter( lambda num: num <> 1, demoList )
> >>> newList
> [2, 3, 4, 5]
> >>>
>
> Jonathan
>





More information about the Python-list mailing list