1

is there a more pythonic way to call a generator (one that may or may not terminate) a specific number of times?

for example: if i want to call endless exaclty N = 7 times i could to it this way:

from itertools import count, accumulate

N = 7
endless = accumulate(count())
for _, out in zip(range(N), endless):
    print(out)

what i do not like about that is that it is a bit error-prone (changing the order of range and the generator will call the generator N+1 times) and that i need to handle the output from range (which i do with the _ variable).

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111

1 Answers1

0

oh, i just may have found a possible answer to that myself:

from itertools import islice, count, accumulate

N = 7
endless = accumulate(count())
for out in islice(endless, N):
    print(out)

(...should i delete the question?)

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • 1
    Regarding deletion - generally no, the duplicate is useful as it is a different way of wording the same question, so it will occur in web searches – Neil Slater Aug 22 '17 at 07:58