Python filter() Function
The filter() function goes through every item of an iterable, runs a test function on it, and keeps only the items for which the test returns True. It returns a filter object (an iterator), which you can loop over or convert to a list.
Syntax
filter(function, iterable)
| Parameter | Description |
|---|---|
| function | A function that returns True or False for each item. Use None to keep all the items that are truthy |
| iterable | A list, tuple, string or any iterable |
Examples
Example 1: keep the passing marks
We keep only the marks that are 33 or above.
marks = [50, 26, 67, 18, 24, 86]
def is_pass(x):
return x >= 33
passing_marks = filter(is_pass, marks)
for m in passing_marks:
print(m)
Output of the above program is
50
67
86
Example 2: with a lambda
numbers = list(range(10))
print(list(filter(lambda x: x % 2 == 0, numbers)))
Output of the above program is
[0, 2, 4, 6, 8]
Example 3: filter words by length
words = ["tree", "sun", "river", "a"]
print(list(filter(lambda w: len(w) > 3, words)))
Output of the above program is
['tree', 'river']
Example 4: filter with None
When the function is None, filter removes every false value like 0, empty string, empty list and None.
data = [0, 1, "", None, "a", [], [3]]
print(list(filter(None, data)))
Output of the above program is
[1, 'a', [3]]
Note:
Like map(), a filter object can be used only once. A list comprehension with an if does the same job: [x for x in numbers if x % 2 == 0].
Summary
filter()keeps only the items that pass a test function.- It returns an iterator, so use
list()to see the result. filter(None, items)removes false values.- Related: map(), reduce() and lambda.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |