I'm trying to get a better grasp on generators in Python because I don't use them enough (I think generators are cool). To do so I wrote a generator for prime numbers:
def primes(): x = 2 while True: for y in xrange(2, x/2 + 1): if x % y == 0: break else: yield x x = x + 1
This works as expected but if I use list comprehension to create a list of primes using this generator it's really slow when compared to sieve function that generates the same list:
[prime.next() for i in xrange(1000)] # exectues in 0.212 sec, sieve in 0.001 sec
I'm assuming that this is not the intended purpose of a generator, but I thought I would see if anyone can think of a way to make this faster.