2

I read this in how to remove element as I traverse a list: Remove elements as you traverse a list in Python

Use this as an example:

>>> colors=['red', 'green', 'blue', 'purple']
>>> filter(lambda color: color != 'green', colors)
['red', 'blue', 'purple']

But how can I do that if i want to remove the element if it is part of a string? i.e I want to filter 'green' if I input just 'een' (just part of 'green' string element in colors?

Community
  • 1
  • 1
michael
  • 106,540
  • 116
  • 246
  • 346

2 Answers2

5

Use a list comprehension instead of using filter():

>>> colors = ['red', 'green', 'blue', 'purple']
>>> [color for color in colors if 'een' not in color]
['red', 'blue', 'purple']

Or, if you want to continue using filter():

>>> filter(lambda color: 'een' not in color, colors)
['red', 'blue', 'purple']
TerryA
  • 58,805
  • 11
  • 114
  • 143
3

A list comprehension is a shorter version of this loop:

new_list = []
for i in colors:
   if 'een' not in i:
       new_list.append(i)

Here is the list comprehension equivalent:

new_list = [i for i in colors if 'een' not in i]

You can also use the filter example, like this:

>>> filter(lambda x: 'een' not in x, colors)
['red', 'blue', 'purple']

Keep in mind this won't change the original colors list, it will just return a new list with only the items that match your filter. You can remove the items that match which will modify the original list, however you need to start from the end to avoid problems with consecutive matches:

for i in colors[::-1]: # Traverse the list backward to avoid skipping the next entry.
    if 'een' in i:
       colors.remove(i)
Steve Barnes
  • 27,618
  • 6
  • 63
  • 73
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284