2

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)?

Alfie Grace
  • 222
  • 1
  • 9
  • Maybe try this - >>> `list(multiples_of_seven)[:15]` – Daniel Hao Sep 09 '21 at 10:12
  • `multiples_of_seven = (x for x in [value for value in range(1000) if value % 7 == 0][:15])` – William Pursell Sep 09 '21 at 10:13
  • 4
    @everyone-above: [`itertools.islice`](https://docs.python.org/3/library/itertools.html#itertools.islice)! – deceze Sep 09 '21 at 10:14
  • You can do it with the generator without any limits put in - `multiples = multiples_of_seven(); [next(multiples) for _ in range(15)]` – Peter Sep 09 '21 at 10:15
  • 2
    `list(itertools.islice(multiples_of_seven(),15))` for a lazy approach. – John Coleman Sep 09 '21 at 10:15
  • Thanks for the help everyone. In the end I went with this for the final line: `[value for value in islice(multiples_of_seven, 15)]` – Alfie Grace Sep 09 '21 at 13:51
  • 1
    That would be a lot simpler with just `list(islice(multiples_of_seven, 15))`. – deceze Sep 09 '21 at 13:53
  • @deceze yeah I've been using list comps throughout the article for displaying the results, it may be worth going back and changing my examples so they use list() instead, thanks for the pointer – Alfie Grace Sep 09 '21 at 13:55

0 Answers0