filter()

Returns an iterator of items for which a function returns a truthy value.

Returns
An iterator of the items that passed the test.
On this page

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, or None.
  • 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 filter with a lambda.

Related entries

#

Spotted a mistake or missing an example? Write to us.