Python Filter Function with Default Parameters for Beginners
Create a reusable filter function with default parameters to keep or exclude numbers above or below a threshold.
Python code
21 linesdef filter_numbers(numbers, threshold=0, reverse=False):
"""Return numbers that pass the threshold filter.
Args:
numbers: list of numbers to filter
threshold: minimum value to keep (default 0)
reverse: if True, keep numbers below threshold (default False)
"""
if reverse:
return [num for num in numbers if num < threshold]
return [num for num in numbers if num >= threshold]
if __name__ == "__main__":
data = [10, -5, 3, -8, 15, 0, 7]
print("Original list:", data)
print("Default filter (>= 0):", filter_numbers(data))
print("Custom threshold (>= 5):", filter_numbers(data, threshold=5))
print("Reverse filter (< 0):", filter_numbers(data, threshold=0, reverse=True))
print("Custom threshold with reverse (< 3):", filter_numbers(data, threshold=3, reverse=True))
Output
Original list: [10, -5, 3, -8, 15, 0, 7]
Default filter (>= 0): [10, 3, 15, 0, 7]
Custom threshold (>= 5): [10, 15, 7]
Reverse filter (< 0): [-5, -8]
Custom threshold with reverse (< 3): [-5, -8, 0]
How it works
This function uses default parameters to make the threshold and direction optional, so callers can filter with minimal setup or customize behavior. The reverse flag flips the comparison operator from >= to <, giving you a single function for both keep-above and keep-below scenarios. List comprehensions keep the logic compact and readable compared to manual loops. The __name__ == "__main__" guard ensures the demo only runs when the script is executed directly, not when imported as a module.
Common mistakes
- Forgetting to include upper-bound numbers like 0 when using default threshold, since it matches `>=`
- Misunderstanding reverse: it filters *below* threshold, it doesn't reverse the list order
- Passing positional arguments instead of keywords, which can make the code harder to read
- Assuming the function mutates the input list—it returns a new list instead
Variations
- Use a lambda with the built-in `filter()`: `list(filter(lambda n: n >= threshold, numbers))`
- Add an `inclusive` parameter to switch between `<` and `<=` for boundary handling
Real-world use cases
- Filtering sensor readings to flag values outside a safe operating range in IoT monitoring scripts.
- Cleaning log data by keeping only entries above a severity threshold before sending to an alert system.
- Selecting test scores above a passing grade from a batch of student results for report generation.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.