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 loopdefloop_example():
for x in [1, 2, 3]:
pass
dis.dis(loop_example)
# Manual equivalent of a for loopprint("\nManual iteration:")
it = iter([10, 20, 30])
whileTrue:
try:
value = next(it)
print(value)
except StopIteration:
break
Output
Click "Run" to execute your code
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.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?