<span>filter()</span>
is a built-in high-order function in Python used to filter sequences, removing elements that do not meet the specified conditions, and returning an iterator object (returns a list in Python 2.x and an iterator in Python 3.x).
Basic Syntax
filter(function, iterable)
How It Works
<span>filter()</span>
takes each element in <span>iterable</span>
as an argument to the <span>function</span>
and retains the elements for which the function returns <span>True</span>
, filtering out those that return <span>False</span>
.
Basic Usage Examples
1. Filtering Even Numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def is_even(n): return n % 2 == 0
even_numbers = filter(is_even, numbers)print(list(even_numbers)) # Output: [2, 4, 6, 8, 10]
2. Using Lambda Functions
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]even_numbers = filter(lambda x: x % 2 == 0, numbers)print(list(even_numbers)) # Output: [2, 4, 6, 8, 10]
3. Filtering Empty Strings
strings = ["hello", "", "world", "", "python", " "]non_empty = filter(lambda s: s.strip() != "", strings)print(list(non_empty)) # Output: ['hello', 'world', 'python']
4. Filtering None Values
values = [0, 1, None, False, True, "", "hello"]filtered = filter(None, values) # When None is used as a function, it filters out elements with a Boolean value of Falseprint(list(filtered)) # Output: [1, True, 'hello']
Advanced Usage
1. Filtering Dictionaries
people = [ {"name": "Alice", "age": 25}, {"name": "Bob", "age": 17}, {"name": "Charlie", "age": 30}, {"name": "David", "age": 15}]adults = filter(lambda p: p["age"] >= 18, people)print(list(adults))# Output: [{'name': 'Alice', 'age': 25}, {'name': 'Charlie', 'age': 30}]
2. Filtering Custom Objects
class Person: def __init__(self, name, age): self.name = name self.age = age
people = [ Person("Alice", 25), Person("Bob", 17), Person("Charlie", 30), Person("David", 15)]adults = filter(lambda p: p.age >= 18, people)for person in adults: print(person.name, person.age)# Output:# Alice 25# Charlie 30
Comparison with List Comprehensions
<span>filter()</span>
can often be implemented using list comprehensions:
# Using filter
even_numbers = filter(lambda x: x % 2 == 0, numbers)
# Using list comprehension
even_numbers = [x for x in numbers if x % 2 == 0]
The choice between the two mainly depends on personal preference and code readability.<span>filter()</span>
may be clearer when dealing with complex conditions, while list comprehensions are more concise for simple filtering.
Notes
-
<span>filter()</span>
returns an iterator (in Python 3.x), and if a list is needed, you can use<span>list()</span>
to convert it. -
If the
<span>function</span>
parameter is<span>None</span>
, it will filter out all elements with a Boolean value of<span>False</span>
. -
<span>filter()</span>
is lazily evaluated, meaning the filtering operation is only executed during actual iteration.
<span>filter()</span>
function embodies the style of functional programming, and when used appropriately, it can make code more concise and expressive.