How To Use Filter Function In Python
The aim of this page📝is to document the general higher-order function
filter() in Python
filter()passes each element of an input collection into a specific, filtering function
- it returns a new iterable object of type of the filtering function
- it returns only those elements of the input collection which the filtering function returns
""" FILTER WITH LAMBDA FILTERING FUNCTION """
>>> positives = filter(lambda x: x > 0, [1, -5, 0, 6])
""" RETURNS LAZY ITERABLE """
<filter object at 0x0250F628>
""" FORCE EVALUATION WITH A LIST CONSTRUCTOR """
3. LIKE AND UNLIKE MAP FUNCTION
- like map(), filter is a general higher order function that accepts/applies a specific function to each element in a sequence
map(), it produces its results lazily (as opposed to Python 2)
filter()only accepts a single input sequence and the function must accept only a single argument
4. NONE AS THE FIRST ARGUMENT
- instead of a specific filtering function, also
Nonecan be passed as the first argument to
- this will filter out input elements that evaluate to
Falsein boolean context
- this means that you can easily remove all False and falsy values from an input collection
>>> trues = filter(None,[0,1,False,True,,[1,2,3],"","hello"])
[1, True, [1, 2, 3], 'hello']
- As a reminder there are 1+6 (False + falsy) values that — if tested — evaluate to