Python Generator Cutoff
Question: I have a generator that will keep giving numbers that follow a specific
formula. For sake of argument let's say this is the function:

    
    
    # this is not the actual generator, just an example
    def Generate():
        i = 0
        while 1:
            yield i
            i+=1       
    

I then want to get a list of numbers from that generator that are below a
certain threshold. I'm trying to figure out a pythonic way of doing this. I
don't want to edit the function definition. I realize you could just use a
while loop with your cutoff as the condition, but I'm wondering if there is a
better way. I gave this a try, but soon realized why it wouldn't work.

    
    
    l = [x for x in Generate() x<10000] # will go on infinitely
    

So is there a correct way of doing this.

Thanks


Answer: An
[`itertools`](http://docs.python.org/2/library/itertools.html#itertools.takewhile)
solution to create another iterator:

    
    
    from itertools import takewhile
    l = takewhile(lambda x: x < 10000, generate())
    

Wrap it in `list()` if you are sure you want a list:

    
    
    l = list(takewhile(lambda x: x < 10000, generate()))
    

Or if you want a list and like inventing wheels:

    
    
    l = []
    for x in generate():
        if x < 10000:
            l.append(x)
        else:
            break
    

