Elegant way to remove items from sequence in Python? [duplicate]

Two easy ways to accomplish just the filtering are:

  1. Using filter:

    names = filter(lambda name: name[-5:] != "Smith", names)

  2. Using list comprehensions:

    names = [name for name in names if name[-5:] != "Smith"]

Note that both cases keep the values for which the predicate function evaluates to True, so you have to reverse the logic (i.e. you say “keep the people who do not have the last name Smith” instead of “remove the people who have the last name Smith”).

Edit Funny… two people individually posted both of the answers I suggested as I was posting mine.

Leave a Comment