EDIT: After reading the suggested link, I have no idea why this has been marked as a duplicate. Sue me.
Can anyone help me understand why filter(None, [list of bools])
removes False
values?
Take the following:
low = 25 high = 35 to_match = [15, 30, 32, 99] def check(low, high, to_match): return [low <= i <= high for i in to_match]
check(low, high, to_match)
returns [False, True, True, False]
filter(None, check(low, high, to_match))
returns [True, True]
So I thought, Python must think False
is None
! But to my surprise, False is None
returns False
!
A) What am I missing?
B) How can I filter only None
values from [True, None, False]
?
filter(None, ...) is shorthand for filter(lambda x: x, ...) -- it will filter out values that are false-y (emphasis mine): filter(function, iterable) Construct a list from those elements of iterable for which function returns true.
The filter() function returns an iterator were the items are filtered through a function to test if the item is accepted or not.
The Python filter() function is the most concise and readable way to perform this particular task. It checks for any None value in list and removes them and form a filtered list without the None values.
If you want to filter out None
, use:
filter(lambda x: x is not None, [list of bools])
or
[x for x in [list of bools] if x is not None]
filter
takes a function, not a value. filter(None, ...)
is shorthand for filter(lambda x: x, ...)
-- it will filter out values that are false-y (emphasis mine):
filter(function, iterable)
Construct a list from those elements of
iterable
for whichfunction
returns true.iterable
may be either a sequence, a container which supports iteration, or an iterator. Ifiterable
is a string or a tuple, the result also has that type; otherwise it is always a list. If function isNone
, the identity function is assumed, that is, all elements ofiterable
that are false are removed.Note that
filter(function, iterable)
is equivalent to[item for item in iterable if function(item)]
if function is notNone
and[item for item in iterable if item]
if function isNone
.
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