Skip to main content

filter()

The filter() function in Python is a built-in function used to filter elements from an iterable (such as a list) for which a provided function returns true. It takes two arguments: the function that determines the filtering criteria and the iterable to be filtered. The function is applied to each element of the iterable, and only the elements for which the function returns true are returned in the result.

Parameter Values

Parameter Description
function

A function that tests if each element of an iterable returns true or false.

iterable

An iterable that is filtered.

Return Values

The filter() function in Python returns an iterator.

How to Use filter() in Python

Example 1:

The filter() function constructs an iterator from elements of an iterable for which a function returns true.

filtered_list = list(filter(lambda x: x % 2 == 0, range(10)))
Example 2:

It takes two parameters: a function that defines the filtering condition and an iterable to be filtered.

filtered_tuple = tuple(filter(lambda x: x.startswith('A'), ['Apple', 'Banana', 'Orange']))
Example 3:

The filter() function returns an iterator, so you need to convert it to a list, tuple, or set to view the filtered results.

filtered_set = set(filter(lambda x: len(x) > 5, ['hello', 'world', 'python']))