Moises Sierpe
Moises Sierpe

Reputation: 3

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?

Upvotes: 0

Views: 52

Answers (2)

Jab
Jab

Reputation: 27485

Like has been said you’re creating the generator each iteration. You need iterate over it each iteration:

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

Although itertools.product will do exactly this for you:

def generador():
    yield from itertools.product(range(3), repeat=3)

Upvotes: 2

Max
Max

Reputation: 739

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))

Upvotes: 1

Related Questions