How does a for loop evaluate its argument

No fear, the iterator will only be evaluated once. It ends up being roughly equivalent to code like this:

it = iter(range(300))
while True:
    try:
        i = next(it)
    except StopIteration:
        break
    ... body of loop ...

Note that it’s not quite equivalent, because break will work differently. Remember that you can add an else to a for loop, but that won’t work in the above code.

Leave a Comment