michael
michael

Reputation: 110550

How to remove an element when I traverse a list

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?

Upvotes: 2

Views: 188

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174624

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)

Upvotes: 3

TerryA
TerryA

Reputation: 59974

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']

Upvotes: 5

Related Questions