Rishi
Rishi

Reputation: 97

How do I print output values of generator functions?

I'm trying to print the yield of a generator function that I get when using next().

I've defined a function as per this:

import itertools

sequence = ['a', 'b', 'c', 'd']

def next_player(seq):
    yield itertools.cycle(seq)

Now, when I call the above function and use next() (for e.g. next(next_player(sequence))), what I get is the memory address (e.g. <itertools.cycle object at 0x7f9409fad440>).

How do I print the actual value within the list (e.g. 'a', 'b', etc.) instead. I know I can iterate over the generator object with a 'for' statement, but I was curious if there's another way to do this using next(), etc.

Upvotes: 0

Views: 199

Answers (2)

Tomer Shetah
Tomer Shetah

Reputation: 8529

Another option you have is declare the cycle prior to your function:

from itertools import cycle
sequence = ['a', 'b', 'c', 'd']
cycle_sequence = cycle(sequence)

def next_item():
    return next(cycle_sequence)

And then use it:

for _ in range(9):
    n = next_item()
    print(n)

will print:

a
b
c
d
a
b
c
d
a

Upvotes: 1

Mike Scotty
Mike Scotty

Reputation: 10782

You want you use yield from:

import itertools

sequence = ['a', 'b', 'c', 'd']

def next_player(seq):
    yield from itertools.cycle(seq)

g = next_player(sequence)
for _ in range(6):
    print(next(g))

Output:

a
b
c
d
a
b

To elaborate: yield from can chain interables, in this case it's the same as writing:

def next_player(seq):
    for x in itertools.cycle(seq):
        yield x

but since itertools.cycle already returns a generator-like object, you could just write

def next_player(seq):
    return itertools.cycle(seq)

Upvotes: 2

Related Questions