Skip to content
Built-in Functions

filter()

Keep items that pass a test.

filter(function, iterable)

filter() constructs an iterator from elements of iterable for which function returns True.

If function is None, all falsy elements are removed.

Parameters

NameDescription
functionA function that returns true or false for each item, or None to keep truthy items.
iterableThe items to test.

Returns

A filter iterator containing the kept items.

Try it

Run it and change it
numbers = [1, 2, 3, 4]
evens = filter(lambda n: n % 2 == 0, numbers)
print(list(evens))

Worth knowing

  • Filtering falsy values: list(filter(None, [0, 1, False, 2, '', 'hello'])) cleanly extracts [1, 2, 'hello'].

Related entries