Search code examples
pythonloopsgenerator

Generator with For In only returning first character instead of the whole string


I want this generator to return these characters in a loop: "><><><" instead it's only returning the first character ">>>>>>"

if I replace yield with print it works correctly, why is it only returning the first character?

def gn():
    while True:
        for char in "><":
            yield char
print([next(gn()) for _ in range(10)])

I've tracked it to a problem in the For In part of the loop, but I still don't see what I'm doing wrong

def gn2():
    for char in [">","<"]:
        yield char
print([next(gn2()) for _ in range(10)])

Solution

  • Each time you call gn(), you create a new generator, which starts at the beginning of the sequence; calling next() on that freshly constructed generator always gives you the first item. Call it once and keep a reference to it:

    >>> g = gn()
    >>> print([next(g) for _ in range(10)])
    ['>', '<', '>', '<', '>', '<', '>', '<', '>', '<']
    

    Or construct a for loop where you're iterating over a single call to gn() instead of calling it inside the loop body:

    >>> print([i for i, _ in zip(gn(), range(10))])
    ['>', '<', '>', '<', '>', '<', '>', '<', '>', '<']