[Python] Why does this itertools function work outside another function but not inside?

Discussão em 'Python' iniciado por Stack, Maio 20, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to find all possible combinations using itertools product in Python. The code works but as soon as I try to yield my results instead of print them it only goes through one cycle or repetition, ignoring the repeat argument.

    This works:

    for i in range(1, 4):
    g = itertools.product(range(5), repeat=i)
    for j in range(len(al) ** i):
    print(next(g))


    This doesn't:

    def func():
    for i in range(1, 4):
    g = itertools.product(range(5), repeat=i)
    for j in range(len(al) ** i):
    yield next(g)

    for i in range(100):
    print(next(func()))


    I have tried playing with the next statements and putting the itertools function in various places. Google isn't very helpful as all results are just very basic itertools tutorials.

    How can I make it work in a function?

    Continue reading...

Compartilhe esta Página