Chaining 501 generators breaks everything?

Jonathan Gardner jgardner at
Fri Feb 19 22:47:46 CET 2010

On Fri, Feb 19, 2010 at 11:47 AM, Andrey Fedorov <anfedorov at> wrote:
> I implemented a Sieve of Eratosthenes primes algorithm using generators:
> This code which chains together 500 generators works fine (~1/20th of a
> second) on my laptop.

You may want a more traditional approach. Until Python gets tail
recursion (doubtful), this won't work very well on any platform.

#!/usr/bin/env python

from itertools import islice, count
from time import time

def primes():
    seen = []
    for i in count(2):
        for s in seen:
            if i%s == 0:
        else: # Run if the for loop doesn't break
            yield i

start = time()
for i in islice(primes(), 0, 10000):
    print i
print time() - start

Jonathan Gardner
jgardner at

More information about the Python-list mailing list