pythonlistsyntactic-sugar

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 ?


Solution

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