2

Is there any way to get the next n values of a generator without looping or calling next() n times? The thing that the generator in this case is infinite, and cannot be translated into a list. Here is the generator function:

def f():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

The following loops both give the desired result, but I would like to know if there is some other method of doing this.

gen = f()
n = 0
while n < 10:
    print(next(gen))
    n += 1

or..

for n, i in enumerate(f()):
    if n < 10:
        print(i)
    else:
        break
Aziz
  • 102
  • 8

1 Answers1

2

There are several ways to do this. One way is to use list comprehension, similar to what you already have above. For instance:

gen = f()
elements = [next(gen) for _ in range(10)]

Another way is to use something like the itertools module, for instance the takeWhile()- or islice()-function.

Also check out How to get the n next values of a generator in a list (python).

Tobias
  • 1,321
  • 6
  • 11