This guide explains filter() function: usage and examples through a focused Python example. You will learn the behavior to expect, why it matters in a real program, and how to recognize the common mistakes before applying it in your own project.
What You Will Learn
filter(predicate, iterable) lazily yields items for which the predicate is truthy. A comprehension expresses the same filtering in many beginner-friendly cases.
When and Why to Use It
The following example focuses on a practical use of filter() Function: Usage and Examples.
Step-by-Step Example
numbers = [3, 8, 10, 13]
def is_even(number):
return number % 2 == 0
selected_numbers = filter(is_even, numbers)
print(list(selected_numbers))
Understanding the Example
Only 8 and 10 satisfy the predicate, so the result list contains those two numbers in their original order.
Expected Output
[8, 10]
Important Behavior and Edge Cases
filter(None, iterable) keeps truthy values, not specifically non-None values; that can accidentally remove zero or empty text.
Try It Yourself
Filter a list of filenames so only names ending in .txt remain.
Common Beginner Mistakes
- filter(None, iterable) keeps truthy values, not specifically non-None values; that can accidentally remove zero or empty text.
- Confusing a returned value with printed output, or failing to verify a function’s behavior with different input values.
- Skipping the practice step and assuming the example covers every input. Test at least one normal case and one edge case relevant to this topic.
Key Takeaways
- filter(predicate, iterable) lazily yields items for which the predicate is truthy.
- Only 8 and 10 satisfy the predicate, so the result list contains those two numbers in their original order.
- Apply the technique deliberately, checking its documented input requirements and failure behavior before integrating it into a larger project.