Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 702
Mat Avatar asked Oct 10 '10 12:10

Mat


People also ask

How do you ignore an item in a list Python?

If you use the list. pop() method to remove an item from a list, you might get an IndexError . You can use a try/except statement to ignore or handle the error.

How do you remove an element from a list without exceptions Python?

The remove() method removes item based on specified value and not by index. If you want to delete list items based on the index, use pop() method or del keyword.


1 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))
like image 69
kennytm Avatar answered Oct 23 '22 09:10

kennytm