filter()
Goes through a list or other iterable and keeps only the items for which a test function returns true, or with None, only the truthy items.
filter(function, iterable)filter(test, items) calls the test function on every item and keeps the items where the answer is true. The items themselves come out unchanged, in their original order.
Pass None instead of a function and it keeps every item that is truthy: it drops 0, "", None, empty lists and False. That is a quick way to clean up empty strings after splitting text.
Like map(), filter() is lazy and returns an iterator, so wrap it in list() to see the results and remember it works only once. A list comprehension with if, [x for x in items if test(x)], does the same job and many people find it clearer.
Parameters
| Parameter | What it is |
|---|---|
functionrequired | A function that takes one item and returns something true or false. Or None, to keep the truthy items. |
iterablerequired | The items to test. |
Return value
A filter object (an iterator) that produces the items that passed.
Examples
1Keep the even numbers
numbers = [3, 8, 15, 22, 7, 40]
evens = list(filter(lambda n: n % 2 == 0, numbers))
print(evens)[8, 22, 40]
2Use a named test function
def in_budget(price):
return price <= 50
prices = [19.99, 75.00, 42.50, 120.00, 8.00]
print(list(filter(in_budget, prices)))[19.99, 42.5, 8.0]
3Drop empty strings with None
line = "Rome,,Paris,,,Oslo,"
parts = line.split(",")
print(parts)
print(list(filter(None, parts)))['Rome', '', 'Paris', '', '', 'Oslo', ''] ['Rome', 'Paris', 'Oslo']
4Keep only the codes made of digits
codes = ["1042", "A17", "993", "", "12b"]
print(list(filter(str.isdigit, codes)))['1042', '993']
str.isdigit is used as the test without brackets; filter() calls it on each code.
5filter() vs a list comprehension
users = [("ana", True), ("ben", False), ("chen", True)]
active = [name for name, ok in users if ok]
print(active)
print([u[0] for u in filter(lambda u: u[1], users)])['ana', 'chen'] ['ana', 'chen']
When you also need to change the items, the comprehension does both jobs in one line.
Common mistakes
filter(None, ...) also drops zeros
None removes every falsy value, and 0 is falsy. If zero is a real value in your data, test for what you actually want to remove.
readings = [12, 0, None, 7, 0]
print(list(filter(None, readings)))
print(list(filter(lambda r: r is not None, readings)))[12, 7] [12, 0, 7, 0]
Expecting a list back
filter() returns an iterator. Printing it shows <filter object at 0x...>, and it is empty after one use.
big = filter(lambda n: n > 10, [5, 20, 30])
print(list(big))
print(list(big))[20, 30] []
Questions people ask
How do I filter a list in Python?
[x for x in items if condition] or list(filter(test, items)). Both keep the order.
How do I remove empty strings from a list?
list(filter(None, items)), or [s for s in items if s]. To also drop strings that only hold spaces: [s for s in items if s.strip()].
Is filter() faster than a list comprehension?
About the same. With a lambda the comprehension is often a little faster and easier to read.