Loops & Iteration Protocols Practice & CPython Execution Tracing
Master iteration mechanics, scope leakage, mutation traps, nested control flow, and generator exhaustion.
CPython Runtime Semantics: Loops & Iteration Protocols
In CPython, iteration is governed by the iterator protocol (dunder iter and dunder next methods) rather than sequential array index pointer arithmetic. When executing a for-loop, CPython emits the GET_ITER opcode to acquire an iterator object, then continually evaluates the FOR_ITER bytecode instruction to push sequential items onto the value stack until a StopIteration signal terminates the block. Understanding generator exhaustion, loop target variable scope leakage into the outer frame, and internal offset mechanics is essential for writing deterministic control flow in robust, scalable Python systems.
Sequence iterators in CPython retain an internal integer offset pointer (it_index). On each iteration, FOR_ITER inspects the underlying sequence, fetches the element at it_index, and increments it_index by one. If items are deleted or inserted into the sequence during iteration, the memory addresses shift immediately while it_index continues incrementing monotonically, causing CPython to silently skip or duplicate elements.
Modifying a list in place while looping over it (for example, invoking lst.remove(item) inside the loop) alters element indices mid-traversal. If index 0 is deleted, the item at index 1 shifts into index 0, but CPython's internal iterator advances to index 1 next, skipping the newly shifted item completely. To avoid this trap, iterate over a shallow slice copy (for item in lst[:]:) or build a filtered list with a list comprehension.
Worked Loops & Iteration Protocols Trace Walkthroughs
Before launching the interactive sandbox, study these worked execution traces. Predict the state mutation for every instruction, then inspect the line-by-line execution table to understand why CPython produces each result.
Walkthrough 1: Modifying List While Iterating
Difficulty: mediumlst = [1, 2, 2, 3]
for x in lst:
if x == 2:
lst.remove(x)
print(lst)[1, 2, 3]The loop processes 1 (index 0), then the first 2 (index 1). The first 2 is removed, shifting the second 2 to index 1 and 3 to index 2. The loop increments its internal index to 2, fetching 3 and skipping the second 2 entirely.
Walkthrough 2: Modifying Dict Size During Iteration
Difficulty: hardd = {'a': 1, 'b': 2}
try:
for k in d:
d['c'] = 3
except RuntimeError:
print('error')errorThe for loop begins iterating over the dictionary's keys. Adding d['c'] = 3 changes the dictionary's size, which Python strictly forbids during iteration, raising a RuntimeError.
Walkthrough 3: Loop Variable Leakage After Loop
Difficulty: mediumi = 10
for i in range(3):
pass
print(i)2The loop iterates i over 0, 1, 2. After the loop finishes, i retains its last assigned value, 2, overwriting the initial value of 10 in the enclosing scope.
Static Problem Bank & Code Walkthrough Preview
The following 8 real problems evaluate core Loops & Iteration Protocols execution behaviors directly from our CPython test suite. Trace each code snippet manually, predict the terminal output, and compare your mental model with the verified output and technical explanation before testing variations in the interactive workspace.
Basic Expression Completion
# Complete expression so result equals the sum of x and y (15)
x = 5
y = 10
result = ___
print(result)x + yx + y evaluates to 15, which is stored in result and printed.
For-Else Semantics Without Break
for i in range(3):
pass
else:
print('else')elsePython's for-else construct triggers the else clause only if the iterable is exhausted without a break. Here, the loop runs 3 times and finishes naturally, so 'else' is printed.
For-Else Semantics With Break
for i in range(3):
if i == 1:
break
else:
print('else')
print('done')else done
When i == 1, the break is executed. This aborts the loop and skips the else block. The program then proceeds to print 'done'.
Check if a String is a Palindrome
# Problem: Determine if a string reads the same forwards and backwards
# Ignore case and non-alphanumeric characters
def is_palindrome(s):
"""
Check if a string is a palindrome.
Args:
s: Input string
Returns:
bool: True if palindrome, False otherwise
"""
# Your implementation heredef is_palindrome(s):
cleaned = ''.join(c.lower() for c in s if c.isalnum())
return cleaned == cleaned[::-1]Clean the string by keeping only alphanumeric chars in lowercase, then compare with its reverse.
Zip Truncation in For Loop
for a, b in zip([1, 2, 3], [4, 5]):
print(a + b, end=' ')5 7zip pairs elements until one list runs out. It pairs (1, 4) and (2, 5). The element 3 is discarded. The loop prints 1+4=5 and 2+5=7.
While-Else With Break
i = 0
while i < 3:
if i == 1:
break
i += 1
else:
print('else')
print(f'Done at {i}')Done at 1When i reaches 1, the break statement terminates the loop immediately. Because the loop was terminated by break, the else block is skipped, and execution continues to print 'Done at 1'.
Range with negative step and edge values
print(list(range(5, -5, -2)))[5, 3, 1, -1, -3]1) Starts at 5. 2) Decrements by 2 each step. 3) Stops before reaching -5 (next would be -5 which is excluded). 4) Includes all values from 5 down to -3 in steps of 2.
Continue in Nested Loops
for i in range(2):
for j in range(2):
if j == 0:
continue
print(f"{i}{j}", end=' ')Checked in sandboxFor i=0, j=0 triggers continue, skipping the print. j=1 prints '01'. For i=1, j=0 triggers continue, skipping the print. j=1 prints '11'.
How to use this tool
Study the verified Loops & Iteration Protocols worked examples above, predict the variable mutations and output on paper, then run variations in the interactive workspace below.
Worked example
# Quick verification check for Loops & Iteration Protocols x = 10 y = x print(x, y)
Static result: 10 10
Controls
Review the test snippet in the editor, click Run to execute in the local Pyodide sandbox, and inspect the stdout console and state changes below.
Honest limits
Exercises for Loops & Iteration Protocols run client-side via WebAssembly (Pyodide). Standard library features are supported; GUI and external network calls are disabled for sandboxing.
Continue with the Python Mastery Hub.
Interactive Dry-Run Execution Workspace
Break Only Affects Innermost Loop
Trace CPython execution step-by-step and deduce the exact stdout string emitted by this snippet.
for i in range(2):
for j in range(2):
if j == 1:
break
print(i, end=' ')Deterministic Trace Tables for Python Code Execution
Master the step-by-step state grid method to track loop counter increments, break/continue conditions, and off-by-one errors with zero guesswork.
Frequently Asked Questions: Loops & Iteration Protocols
Why does deleting items from a list inside a for-loop skip elements in Python?
CPython sequence iterators maintain an internal integer counter that increments on every step. When you remove an item, all subsequent elements shift left by one position. On the next step, the counter advances to the next index, skipping over the element that just shifted into the current index slot. Always iterate over a copy or use list comprehensions.
How do for-loop target variables behave regarding scope in Python?
Python loops do not introduce a new local scope. The loop variable leaks into the surrounding function or module namespace and retains the value from the loop's final iteration. If the iterable is empty, the variable is never assigned.
What is the concrete difference between an Iterable and an Iterator in CPython?
An Iterable is any object implementing __iter__() that produces a fresh iterator (such as lists, tuples, or dicts). An Iterator implements both __iter__() (returning itself) and __next__(), maintaining an active cursor and raising StopIteration when exhausted. Iterators are single-pass streams.