Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: filter(None, [list of bools]) behavior

Tags:

python

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]?

like image 325
AutomaticStatic Avatar asked Jul 12 '16 21:07

AutomaticStatic


People also ask

What is filter () none in Python?

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.

What is filter () function in Python?

The filter() function returns an iterator were the items are filtered through a function to test if the item is accepted or not.

How do I remove all none values from a list in Python?

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.


1 Answers

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 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.

Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item for item in iterable if item] if function is None.

like image 172
agf Avatar answered Oct 04 '22 05:10

agf