all Python 3Functionsfunction
filter()
functional
Keeps the items for which the function returns True. Returns an iterator.
Syntax
filter(func, iterable)
The result is a lazy iterator: it's computed as you traverse it and is exhausted after the first pass, so a second list() over it yields nothing. Special case — filter(None, iterable): with no function it drops every falsy element (0, '', None, empty containers).
Examples
nums = [1, -2, 3, -4, 5]
pos = list(filter(lambda x: x > 0, nums))
print(pos) # → [1, 3, 5]
evens = list(filter(lambda x: x % 2 == 0, range(10)))
print(evens) # → [0, 2, 4, 6, 8]
words = ['', 'hello', '', 'world']
non_empty = list(filter(None, words))
print(non_empty) # → ['hello', 'world']
# filter с функцией
def is_odd(n): return n % 2 != 0
odds = list(filter(is_odd, range(10)))
print(odds) # → [1, 3, 5, 7, 9]
# filter ленивый
f = filter(lambda x: x > 2, [1,2,3,4])
print(next(f)) # → 3
# Отбор непустых словарей
data = [{'a':1}, {}, {'b':2}]
non_empty_d = list(filter(None, data))
print(non_empty_d) # → [{'a':1},{'b':2}]
# filter + map
result = list(map(lambda x: x**2, filter(lambda x: x%2==0, range(6))))
print(result) # → [0, 4, 16]
print(list(filter(str.isdigit, "a1b2c3"))) # → ['1', '2', '3']
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy