Limiting Generator Expressions

Viewed 22

I'm working on putting together an article teaching readers how to write custom generators and I was wondering if there is a way to limit a generator expression so that it will only yield the first N values in a sequence.

To demonstrate generator expressions I've created two examples for creating a generator with the first 15 multiples of seven, one using a function and one using an expression.

Function:

def multiples_of_seven():
    multiples_found = 0
    for i in range(1000):
        if i % 7 == 0:
            # i is a multiple of 7
            multiples_found += 1
            yield i
        
        if multiples_found == 15: # break once 15 multiples are found
            break

[value for value in multiples_of_seven()] # display the results

Expression:

multiples_of_seven = (value for value in range(1000) if value % 7 == 0)

[value for value in multiples_of_seven][:15] # display the results

At the moment I've added [:15] to the end of the list comp to limit the number of multiples found, but I was wondering if there was something I could add to the generator expression to limit the number of yielded values to 15 (like in the function)?

0 Answers
Related