[Python] iter, range in for loop

Discussão em 'Python' iniciado por Stack, Novembro 30, 2025.

  1. Stack

    Stack Membro Participativo

    I thought the for in statement takes in iterables not iterators, but somehow the following code works fine. I am confused. Actually, I was looking at the generator example in PEP 289:

    >>> for i in range(10):
    print(i)


    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    >>> for i in iter(range(10)):
    print(i)


    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    >>>


    Can anyone explain what happened when using iter(range(10)) in the for loop?

    Continue reading...

Compartilhe esta Página