[Tutor] removing items from a list

Gonçalo Rodrigues op73418@mail.telepac.pt
Sat, 12 Oct 2002 14:40:33 +0100


> Dear listreaders,
> I want to remove items from a list that have content that matches my
> data.  I can think of a few ways to do this, but none that seem as
> simple as it should be.
>
> This doesn't work, I'm not sure why.  Mabye item isn't a refence to the
> list item, but just has the same value.
>
> for item in list:
> if item == data: del item
>
> This works, its ok, but still seems like there should be something
> cleaner if not faster.
> i=0
> for item in list:
> if item == data:
> del list[i]
> i=i+1
>
>
> This seems inefficient:
>
> i=0
> for item in list:
> if not item == data:
> newlist[i] = item
> i = i + 1
> list = newlist
>
> --Galen

Removing an item from the list is always somewhat inefficient. You have to
linearly search the list, then remove the item, both O(N) operations (I am
being a little sloppy - I know). If your framework affords it, just stuff
your items in a dictionary as keys (in particular they have to be hashable).
In this way, testing equality and removing is essentialy independent of the
size of the dictionary.

If you must absolutely go with a list then use the remove method.

Hope it helps,
Gonçalo Rodrigues