How to Generate Primes with a Generator in Python

Generate prime numbers up to a limit using the Sieve of Eratosthenes wrapped in a generator expression for lazy evaluation.

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

Python code

16 lines
Python 3.9+
def prime_generator(limit):
    sieve = [True] * (limit + 1)
    sieve[0] = sieve[1] = False

    for i in range(2, int(limit ** 0.5) + 1):
        if sieve[i]:
            for j in range(i * i, limit + 1, i):
                sieve[j] = False

    return (num for num, is_prime in enumerate(sieve) if is_prime)


if __name__ == "__main__":
    limit = 30
    primes = list(prime_generator(limit))
    print(f"Primes up to {limit}: {primes}")

Output

stdout
Primes up to 30: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

How it works

The code builds a boolean sieve where each index represents a number and True marks it as prime. It iterates only up to the square root of the limit, marking multiples of each prime as composite. The generator expression (num for num, is_prime in enumerate(sieve) if is_prime) lazily yields each prime when iterated, avoiding a full list in memory. This combines the efficiency of the sieve algorithm with the memory benefits of generators, ideal for large limits.

Common mistakes

  • Forgetting to mark 0 and 1 as not prime before starting the sieve
  • Iterating the inner loop from `i` instead of `i*i`, causing redundant work
  • Returning a list instead of a generator, defeating the lazy-evaluation goal

Variations

  1. Use a set or list comprehension to return a list directly when memory isn't a concern
  2. Implement the same logic with `itertools.compress` for a more concise generator

Real-world use cases

  • Generating a list of primes for cryptography key generation in security modules.
  • Precomputing prime numbers for hashing algorithms or collision-free table sizing.
  • Streaming primes in a data pipeline to filter or analyze number-theoretic sequences.

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.