1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] `map` causing infinite loop in Python 3

Discussão em 'Python' iniciado por Stack, Fevereiro 11, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following code:

    def my_zip(*iterables):
    iterators = tuple(map(iter, iterables))
    while True:
    yield tuple(map(next, iterators))


    When my_zip is called, it just creates an infinite loop and never terminates. If I insert a print statement (like shown below), it is revealed that my_zip is infinitely yielding empty tuples!

    def my_zip(*iterables):
    iterators = tuple(map(iter, iterables))
    while True:
    t = tuple(map(next, iterators))
    print(t)
    yield t


    However, the equivalent code with a generator expression works fine:

    def my_genexp_zip(*iterables):
    iterators = tuple(iter(it) for it in iterables)
    while True:
    try:
    yield tuple(next(it) for it in iterators)
    except:
    print("exception caught!")
    return


    Why is the function with map not behaving as expected? (Or, if it is expected behavior, how could I modify its behavior to match that of the function using the generator expression?)

    I am testing with the following code:

    print(list(my_genexp_zip(range(5), range(0, 10, 2))))
    print(list(my_zip(range(5), range(0, 10, 2))))

    Continue reading...

Compartilhe esta Página