PyCodeItPython trace & SQL practice
Python 3.12+ CPython TrackPyodide WASM Sandbox61 Tracing Problems

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.

Iterator Protocol & Index Offset Management

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.

Structural Mutation of Lists During For-Loop Iteration

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: medium
lst = [1, 2, 2, 3]
for x in lst:
    if x == 2:
        lst.remove(x)
print(lst)
Verified CPython Output:
[1, 2, 3]
Technical Walkthrough & Execution Analysis:

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: hard
d = {'a': 1, 'b': 2}
try:
    for k in d:
        d['c'] = 3
except RuntimeError:
    print('error')
Verified CPython Output:
error
Technical Walkthrough & Execution Analysis:

The 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: medium
i = 10
for i in range(3):
 pass
print(i)
Verified CPython Output:
2
Technical Walkthrough & Execution Analysis:

The 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.

Problem 1easy

Basic Expression Completion

# Complete expression so result equals the sum of x and y (15)
x = 5
y = 10
result = ___
print(result)
Expected Output: x + y

x + y evaluates to 15, which is stored in result and printed.

Problem 2medium

For-Else Semantics Without Break

for i in range(3):
 pass
else:
 print('else')
Expected Output: else

Python'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.

Problem 3hard

For-Else Semantics With Break

for i in range(3):
    if i == 1:
        break
    else:
        print('else')
        print('done')
Expected Output:
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'.

Problem 4easy

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 here
Expected Output:
def 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.

Problem 5medium

Zip Truncation in For Loop

for a, b in zip([1, 2, 3], [4, 5]):
 print(a + b, end=' ')
Expected Output: 5 7

zip 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.

Problem 6hard

While-Else With Break

i = 0
while i < 3:
    if i == 1:
        break
    i += 1
else:
    print('else')
print(f'Done at {i}')
Expected Output: Done at 1

When 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'.

Problem 7easy

Range with negative step and edge values

print(list(range(5, -5, -2)))
Expected Output: [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.

Problem 8medium

Continue in Nested Loops

for i in range(2):
    for j in range(2):
        if j == 0:
            continue
            print(f"{i}{j}", end=' ')
Expected Output: Checked in sandbox

For 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

Problem 4 / 61+30 XP

Break Only Affects Innermost Loop

medium
Task: Output Execution Prediction

Trace CPython execution step-by-step and deduce the exact stdout string emitted by this snippet.

Socratic Guidance-5 XP penalty per revealed hint
Topic Problems0 / 61 Solved
main.pyCPython 3.12 (WASM)
1
2
3
4
5
for i in range(2):
    for j in range(2):
        if j == 1:
            break
        print(i, end=' ')
Press Enter to submit
Match exact whitespace and capitalization
In-Depth Learning Guide

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.

Read Full Guide

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.