filter() (Python)
filter() keeps only the items from a sequence for which a function returns True. It is used to select a subset of values based on a condition.
Python
Like map(), filter() returns a lazy object, so wrap it in list() to view the results. A list comprehension with an if clause is often the more Pythonic alternative.
Syntax
filter(function, iterable)Examples
Python
nums = [1, 2, 3, 4]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)Output:
[2, 4]