Removing from a List in Place

Tim Williams tim at tdw.net
Tue Sep 5 17:09:40 EDT 2006


On 05/09/06, Tim Williams <tim at tdw.net> wrote:
> On 05/09/06, Gregory Piñero <gregpinero at gmail.com> wrote:> I'm going
> to assume that it's supposed to work like this, but could
> > someone tell me the reasoning behind it?  I.E. why is 3 skipped?
> >
> > >>> alist=[1,2,3]
> > >>> for item in alist:
> > ....    print item
> > ....    if item==2:
> > ....            alist.remove(item)
> > ....
> > 1
> > 2
> > >>>
>
>
> >
> > Bonus Question:
> > Can we make this behave more intuitiviely in Python 3000?
>
> It does already,  you just haven't grasped list fully yet :):)
>
> when you remove 2 from alist,  the list becomes length 2, there is no
> longer a 3rd item in the list to iterate over.
>
> Try this
>
> > >>> alist=[1 ,2 ,3, 4]
> > >>> for item in alist:
> > ....    print item
> > ....    if item==2:
> > ....            alist.remove(item)
> > ....    print alist
>

sorry,  I meant to offer an alternative also

in yourgiven case you can iterate over a copy of the list like this:

>>> for item in alist[:] :



More information about the Python-list mailing list