Search code examples
python-3.xgeneratoryield

Why does this generator work with a for loop but not with next()?


I am trying to make a generator that gives me the permutations of 3 numbers

def generador():
    for i in range(3):
        for j in range(3):
            for k in range(3):
                yield i,j,k

with a for loop for a,b,c in generador(): it work's just fine but:

for _ in range(27):
    print(next(generador()))

just prints (0,0,0) over an over again. Why?


Solution

  • You need to latch the generator to a variable and next through that so youre going through the same instance, otherwise you're going through a new instance each loop, hence you're getting 0,0,0

    def generador():
        for i in range(3):
            for j in range(3):
                for k in range(3):
                    yield i,j,k
    a = generador()
    for _ in range(27):
        print(next(a))