Ignore an element while building list in python

Mat picture Mat · Oct 10, 2010 · Viewed 11.1k times · Source

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 ?

Answer

kennytm picture kennytm · Oct 10, 2010

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))