Compare filter() with comprehensions for selecting items.
What You Will Learn
filter(predicate, iterable) returns a lazy iterator of matching elements. A list comprehension collects results immediately, while a generator expression provides a lazy alternative. filter(None, iterable) keeps truthy items.
Choose the form that makes the selection criterion easiest to read.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
scores = [0, 58, 81, 92, 40]
filtered_scores = filter(lambda score: score >= 60, scores)
selected_scores = [score for score in scores if score >= 60]
print(list(filtered_scores))
print(selected_scores)
How the Example Works
- The variable scores holds the result of [0, 58, 81, 92, 40]. Later lines use that value or inspect how it changes.
- The variable filtered_scores holds the result of filter(lambda score: score >= 60, scores). Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
Expected output from the example:
[81, 92]
[81, 92]
When You Would Use This
These tools are useful when composing small reusable functions, adapting callbacks, or eliminating repeated work. Pay attention to whether the operation returns a new object, updates state, or produces lazy results. Test a small success case and a boundary case before integrating it into an application.
Practice: Modify the Code
Filter a list of transactions with both approaches.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Assuming filter(None, values) removes only None; it also removes other falsey values.
- Assuming the operation has the same behavior for missing values, empty inputs and regular inputs.
Key Takeaways
- Compare filter() with comprehensions for selecting items.
- filter(predicate, iterable) returns a lazy iterator of matching elements.
- Choose the form that makes the selection criterion easiest to read.