Mat
Mat

Reputation: 1101

Ignore an element while building list in python

I need to build a list from a string in python using the [f(char) for char in string] syntax and I would like to be able to ignore (not insert in the list) the values of f(x) which are equal to None.

How can I do that ?

Upvotes: 21

Views: 14528

Answers (2)

Crandel
Crandel

Reputation: 997

You can add a conditional in the for, to check of each element is not None or empty

[element for element in list_of_elements) if element]

this allow to avoid a double looping

Example. Remove even numbers from a list:

f = lambda x: x % 2
list_of_elements = [1, 2, 3, 4, 5, 7, 34, 45, 55, 65, 66]
c = [element for element in list_of_elements if f(element)]

Output:

[1, 3, 5, 7, 45, 55, 65]

Upvotes: 0

kennytm
kennytm

Reputation: 523484

We could create a "subquery".

[r for r in (f(char) for char in string) if r is not None]

If you allow all False values (0, False, None, etc.) to be ignored as well, filter could be used:

filter(None, (f(char) for char in string) )
# or, using itertools.imap,
filter(None, imap(f, string))

Upvotes: 40

Related Questions