how to remove multiple occurrences of a string within a list?

waylan waylan at gmail.com
Thu Apr 5 15:45:52 EDT 2007


On Apr 3, 6:05 pm, Steven Bethard <steven.beth... at gmail.com> wrote:
> bahoo wrote:
> > The larger problem is, I have a list of strings that I want to remove
> > from another list of strings.
>
> If you don't care about the resulting order::
>
>      >>> items = ['foo', 'bar', 'baz', 'bar', 'foo', 'frobble']
>      >>> to_remove = ['foo', 'bar']
>      >>> set(items) - set(to_remove)
>      set(['frobble', 'baz'])

I'm surprised no one has mentioned any of the methods of set. For
instance:

    >>> set.difference.__doc__
    'Return the difference of two sets as a new set.\n\n(i.e. all
elements that are in this set but not in the other.)'
    >>>set(items).difference(to_remove)
    set(['frobble', 'baz'])

There are a few other cool methods of sets that come in handy for this
sort of thing. If only order could be preserved.
>
> If you do care about the resulting order::
>
>      >>> to_remove = set(to_remove)
>      >>> [item for item in items if item not in to_remove]
>      ['baz', 'frobble']
>
> STeVe





More information about the Python-list mailing list