forExpert Examples

Starts a loop that iterates over a sequence or iterable

For loop internals

How the for loop works under the hood.

python
import dis

# The for loop protocol:
# 1. Call iter() on the iterable -> get iterator
# 2. Call next() on iterator -> get value
# 3. On StopIteration -> exit loop

def loop_example():
    for x in [1, 2, 3]:
        pass

dis.dis(loop_example)

# Manual equivalent of a for loop
print("\nManual iteration:")
it = iter([10, 20, 30])
while True:
    try:
        value = next(it)
        print(value)
    except StopIteration:
        break

for calls iter() to get an iterator, then repeatedly calls next() until StopIteration is raised. GET_ITER and FOR_ITER are the key bytecode instructions.

Want to try these examples interactively?

Open Expert Playground