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 ?
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.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With