Python Filter Function
What does filter() do?
The filter()
function constructs an iterator from elements of an iterable for which a function returns True. It's used to filter out items that don't meet a condition.
Basic Syntax
filter(function, iterable)
function
: A function that returns True or False for each item.iterable
: The sequence to filter.
filter()
returns an iterator. Convert it to a list or tuple to see the results.
The function must return True/False
def is_even(n):
return n % 2 == 0
numbers = [1, 2, 3, 4, 5]
evens = filter(is_even, numbers)
print(list(evens)) # Output: [2, 4]
Returning an iterator
The result is a filter object (iterator):
result = filter(None, [0, 1, '', 'hello'])
print(list(result)) # Output: [1, 'hello']
Converting filter object to list/tuple
You often convert the result to a list or tuple:
words = ["apple", "", "banana", "cherry", ""]
non_empty = filter(None, words)
print(list(non_empty)) # Output: ['apple', 'banana', 'cherry']
Examples with lambda functions
numbers = [1, 2, 3, 4, 5]
filtered = filter(lambda x: x > 2, numbers)
print(list(filtered)) # Output: [3, 4, 5]
Summary
filter()
selects items from an iterable for which the function returns True.- Returns an iterator; convert to list/tuple to see results.
- If function is None, removes items that are falsey.
- Useful for filtering data without explicit loops.