I am somewhat new to python and have been working with lists of strings like the first list and am looking to filter it down to only the truthy values as depicted in the second.
l = ['value1', 'value2', '', None, 'value3']
l = ['value1', 'value2', 'value3']
I have been doing it the following ways previously (the second more recently)
new_l = filter(lambda x: x, l)
new_l = filter(bool, l)
Is there a more pythonic approach to this solution?
If first argument is None
filter
automatically removes all the elements that evaluate to False
in boolean context. I would consider that the most pythonic approach:
>>> filter(None, [1, 3, 0, 5, 3])
[1, 3, 5, 3]
Excerpt from Python docs:
Construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If iterable is a string or a tuple, the result also has that type; otherwise it is always a list. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.
Alternative option would be list comprehension on Python 2 and generator expression on Python 3. The benefit of using them would be that they behave the same no matter what Python version you are using unlike filter
that returns iterator
on Python 3 instead of a list:
>>> l = [1, 3, 0, 5, 3]
>>> [x for x in l if x]
[1, 3, 5, 3]
>>> list(x for x in l if x)
[1, 3, 5, 3]
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