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 |
iterable | An |
Return Values
The filter()
function in Python returns an iterator.
How to Use filter()
in Python
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)))
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']))
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']))