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.
Python code
16 linesdef 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
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
- Use a set or list comprehension to return a list directly when memory isn't a concern
- 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
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.