How to filter a generator with a predicate function in Python

This code defines a generator function that yields only items from an iterable that satisfy a given predicate, then tests it with even and positive number filters.

Medium Python 3.9+ Aug 9, 2026 Comprehensions & generators 10 views 0 copies

Python code

20 lines
Python 3.9+
def filter_gen(predicate, iterable):
    for item in iterable:
        if predicate(item):
            yield item

def is_even(num):
    return num % 2 == 0

def is_positive(num):
    return num > 0

if __name__ == "__main__":
    numbers = range(-5, 10)
    
    even_numbers = list(filter_gen(is_even, numbers))
    positive_numbers = list(filter_gen(is_positive, numbers))
    
    print(f"Numbers: {list(numbers)}")
    print(f"Even numbers: {even_numbers}")
    print(f"Positive numbers: {positive_numbers}")

Output

stdout
Numbers: [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Even numbers: [-4, -2, 0, 2, 4, 6, 8]
Positive numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9]

How it works

The filter_gen function is a generator, so it yields one item at a time instead of building a full list in memory. Each call to predicate(item) evaluates to True or False, and only items that return True are yielded. Laziness means the filtering happens only as you iterate, which is efficient for large data. The list() call around the generator converts the yielded items into a concrete list for printing.

Common mistakes

  • Forgetting that a generator can only be iterated once, so reusing it after `list()` yields nothing.
  • Passing a function call like `is_even()` instead of the function reference `is_even`.
  • Assuming the predicate must return a boolean—truthy values also work.
  • Not converting the generator to a list before printing, which shows a generator object instead of values.

Variations

  1. Use Python's built-in `filter(predicate, iterable)` to achieve the same result.
  2. Use a generator expression: `(item for item in iterable if predicate(item))`.

Real-world use cases

  • Filtering streaming log lines that match a severity threshold in a real-time monitoring pipeline.
  • Processing large data files line-by-line, keeping only records that pass validation criteria.
  • Selecting valid user inputs from a form submission without loading all values into memory.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.