title: filter
description: filter() is Python's built-in higher-order function for filtering elements in a sequence. It takes a function and an iterable object as arguments, and returns an iterator (in Python 3) containing all elements for which the function returns True.
Python filter() function detailed explanation and practical cases
In the Python functional programming toolbox,filter()It is one of the core tools for handling sequence "filtering" scenarios - it does not modify elements, but only accurately retains or eliminates them according to rules, andmap()are two complementary commonly used higher-order functions.
1. Filter() function basics
Core definition
filter()It is a built-in higher-order function in Python that receives two parameters:
- Determination function: return
True/False(or an object implicitly converted to a Boolean value, such as the empty string,0、NoneAllFalse) - Iterable objects: such as lists, tuples, generators, strings, etc.
In Python 3,filter()The filtered sequence will not be returned directly, but a lazy iterator will be returned - only when it is actually traversed (such asnext()、forThe result is calculated only when looping or converting into a list/tuple), which can significantly save the memory of large data sets.
Basic syntax
Core differences with map()
We use tables to compare more intuitively:
2. Basic introduction: two simple scenarios
Scenario 1: Filter odd numbers in the list
Here we first use an explicit custom function to make it easier to understand the decision logic:
Scenario 2: Filter invalid strings (null values, all spaces)
When processing crawlers or form data, you often encounter empty content that needs to be cleaned.filter()It’s easy to handle:
3. Advanced features: the charm of lazy evaluation
Why Python 3filter()Changed to return iterator? The core is memory optimization - there is no need to load all qualifying elements into memory at once.
For example, we can step by step observe the execution process of the iterator:
Tip: This "whatever you use" lazy evaluation mechanism is particularly useful when processing large files, database cursors, or infinite sequences - you don't need to wait for all the data to be ready before starting processing.
4. Everyday simplification: combine lambda expressions
If the decision logic is very simple (no need for reuse), there is no need to write a separate custom function. lambda + filter is the golden combination:
5. Classic practical case: Sieve of Eratosthenes (generating infinite prime numbers)
This isfilter()An excellent example combined with an infinite generator - it can efficiently generate any range of prime numbers with very low memory usage:
Key points to understand: The whole process is like sifting through layers - the first layer removes even numbers (except 2), the second layer removes multiples of 3, the third layer removes multiples of 5...use it every time
filter()Apply a new layer of filtering conditions, and the infinite sequence is "screened" cleanly.
6. Modern Python Alternative: List/Generator Expressions
Althoughfilter()It's classic, but for simple filters that require only one result, list comprehensions or generator expressions are usually more readable (in line with Python's "readability first" principle):
One sentence suggestion: If your filtering condition is just a line of expression, use derivation; if the decision logic requires multi-step calculation or will be reused in multiple places, use
filter()+ Custom functions.
7. Hands-on exercise: screening palindromes
Palindrome numbers refer to numbers that are read the same forward and back (such as 121, 1331). We can usefilter()Quick implementation:
8. Performance and usage scenario suggestions
Performance comparison
- Memory efficiency:
filter()and generator expressions are better than list comprehensions (the latter two do not require all results to be prestored) - Speed efficiency: The difference between the three is very small in simple scenarios, and the list comprehension may be slightly faster (because no additional function call overhead is required)
Use scene selection
9. Summary
filter()It is an indispensable filtering tool in Python functional programming, but it does not need to be used blindly in modern Python development - readability always comes first.
Core Points Review:
- Receive "decision function" and "iterable object"
- Python 3 returns lazy iterator, memory friendly
- Can be used in combination with lambda, custom functions, and unlimited generators
- Simple scenarios prioritize list/generator expressions
10. Further reading
- Python official documentation: Built-in Functions — filter()
- Additional filtering tools:
itertools.filterfalse()(The return judgment function isFalseelements) - The Three Musketeers of Functional Programming:
map()、filter()、functools.reduce()(Python 3 needs to be imported)

