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
An
itertoolssolution to create another iterator:Wrap it in
list()if you are sure you want a list:Or if you want a list and like inventing wheels: