Ignore an element while building list in python

Question:

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 ?

Asked By: Mat

||

Answers:

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))
Answered By: kennytm

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]
Answered By: Crandel
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.