Deleting from a list (correction)

Brad Bollenbach bbollenbach at home.com
Tue Jan 1 22:25:38 EST 2002


"Brad Bollenbach" <bbollenbach at home.com> wrote in message
news:BPuY7.18080$L4.1822646 at news2.calgary.shaw.ca...
> <bvdpoel at uniserve.com> wrote in message
> news:3C326CF0.A28B9FC7 at uniserve.com...
> >
> > Does python have a notion as to where the current item in a list is?
> [snip examples attempts at removing an item from a list]
>
> You could do, simply:
>
> foo = [1, 2, 3, 4]
>
> for i in range(foo):
>     if foo[i] == 3:
>         del foo[i]
>
> foo would then contain [1, 2, 4]

Bah, silly me. Scrap that.

Depending on what you want to do, you may consider either:

a.) using del foo[i] if you know i in advance (that is, no looping
required).
b.) use filter(func, foo) to construct a list consist of those elements for
which func returns true (chances to use filter() shouldn't be passed up! :).
c.) use foo.remove("value") to remove the item with the smallest index if
that's suitable for your situation.





More information about the Python-list mailing list