PythonBuilt-in functions
filter()
Returns an iterator of items for which a function returns a truthy value.
- Returns
- An iterator of the items that passed the test.
Example
#Python
scores = [45, 82, 67, 91, 30]
passed = list(filter(lambda s: s >= 60, scores))
print(passed)
values = ["Emma", "", None, "Jack", 0]
print(list(filter(None, values)))Resultsaved result, you can check it
[82, 67, 91]
['Emma', 'Jack']
Definition and usage
#The filter(function, collection) function lets through only the items for which the function returns a truthy value. The result is an iterator, usually converted to a list.
If you pass None instead of a function, filter removes every falsy value: zeros, empty strings, None, and empty collections.
Just like with map, a list comprehension with if is often more readable: [x for x in items if x > 0].
Syntax
#Syntax
filter(function, iterable)Parameters
#function
callable or None
The test function, orNone.iterable
a collection
The items to filter.
Good practices
#filter(None, items)is a quick way to drop empty values.- For complex conditions, a list comprehension is more readable than
filterwith a lambda.
Related entries
#- map()Calls a function for every item and returns an iterator of results.
- List comprehensionsA concise way to build lists, sets, and dictionaries from other collections.
- any()Checks whether at least one item in a collection is truthy.
- lambdaA short anonymous function written as a single expression.
- next()Fetches the next item from an iterator. Once it is exhausted, returns a default value or raises StopIteration.
Spotted a mistake or missing an example? Write to us.