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

Lists Foundations & Memory Mechanics Practice & CPython Execution Tracing

Master list allocation, reference aliasing, mutation quirks, slicing edge cases, sorting stability, and in-place operations.

CPython Runtime Semantics: Lists Foundations & Memory Mechanics

Python lists (PyListObject) are dynamic arrays of pointers to PyObject values. CPython 3.12 avoids resizing the pointer buffer on every append by over-allocating. In listobject.c, the requested size is increased by newsize >> 3 plus 3 for small lists or 6 for larger lists, then aligned with (new_allocated + 3) & ~3. A follow-up check can choose a smaller allocation when the proposed growth would not leave enough room for the current batch. This makes append amortized O(1), while arbitrary insertions and deletions still move O(n) pointers.

Contiguous Pointer Buffer & Over-Allocation Geometry

Because a PyListObject stores memory addresses rather than serialized values, elements can be heterogeneous. When performing slice assignment or slicing (lst[a:b]), CPython allocates a new PyListObject header and copies pointer references rather than duplicating the underlying objects. Mutating a mutable child object within a shallow copy reflects across both references.

Nested List Replication via Multiplication ([[0] * n] * m)

Constructing two-dimensional grids with [[0] * 3] * 3 creates an outer list populated with three identical pointer references pointing to the exact same inner list on the heap. Mutating grid[0][0] = 1 updates every row simultaneously. Multi-dimensional matrices must always be instantiated via comprehension: [[0 for _ in range(3)] for _ in range(3)].

Worked Lists Foundations & Memory Mechanics 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: The Nested List Multiplication Alias Trap

Difficulty: hard
a = [[1] * 2] * 2
a[0][0] = 9
print(a)
Verified CPython Output:
[[9, 1], [9, 1]]
Technical Walkthrough & Execution Analysis:

`[[1] * 2]` creates a single inner list `[1, 1]`. The outer `* 2` duplicates the reference to this inner list, resulting in `[inner, inner]`. Modifying `a[0][0]` mutates the shared inner list, so both `a[0]` and `a[1]` reflect the change.

Walkthrough 2: Slice Assignment with Step and Length Matching

Difficulty: medium
a = [1, 2, 3, 4, 5]
a[1::2] = [20, 30]
print(a)
Verified CPython Output:
[1, 20, 3, 30, 5]
Technical Walkthrough & Execution Analysis:

The slice `a[1::2]` selects elements at index 1 and 3 (values 2 and 4). The assignment replaces these specific positions with 20 and 30 respectively, leaving the other elements untouched.

Walkthrough 3: Augmented Assignment vs Standard Concatenation

Difficulty: hard
a = [1, 2]
b = a
a += [3]
c = a
a = a + [4]
print(b)
print(c)
Verified CPython Output:
[1, 2, 3]
[1, 2, 3]
Technical Walkthrough & Execution Analysis:

`a += [3]` mutates the original list, so `b` (which references it) sees `[1, 2, 3]`. `c = a` makes `c` point to this same mutated list. `a = a + [4]` creates a new list `[1, 2, 3, 4]` and rebinds `a`, but `b` and `c` still reference the old list `[1, 2, 3]`.

Static Problem Bank & Code Walkthrough Preview

The following 8 real problems evaluate core Lists Foundations & Memory Mechanics 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

Boolean Truthiness of Nested and Zero Lists

print(bool([]), bool([[]]), bool([0]))
Expected Output: False True True

`[]` is empty -> False. `[[]]` has one element (an empty list) -> True. `[0]` has one element (the integer 0) -> True. Python does not recursively evaluate truthiness for container types.

Problem 3hard

Sort Stability and Tuple Key Extraction

a = [(1, 'a'), (2, 'b'), (1, 'c'), (2, 'a')]
a.sort(key=lambda x: x[0])
print(a)
Expected Output: [(1, 'a'), (1, 'c'), (2, 'b'), (2, 'a')]

The sort groups elements by their first tuple value. Because the sort is stable, `(1, 'a')` remains before `(1, 'c')`, and `(2, 'b')` remains before `(2, 'a')`, exactly as they appeared in the original list.

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

Inserting at a Negative Index

a = [1, 2, 3]
a.insert(-1, 9)
print(a)
Expected Output: [1, 2, 9, 3]

The list is `[1, 2, 3]`. Index -1 is the value `3`. `insert(-1, 9)` places `9` immediately before `3`, resulting in `[1, 2, 9, 3]`.

Problem 6hard

Sequential Deletion Methods Side Effects

a = [1, 2, 3, 2, 1]
del a[1]
a.remove(2)
a.pop()
print(a)
Expected Output: [1, 3]

Initial: `[1, 2, 3, 2, 1]`. `del a[1]` -> `[1, 3, 2, 1]`. `a.remove(2)` finds the remaining `2` and removes it -> `[1, 3, 1]`. `a.pop()` removes the last element `1` -> `[1, 3]`. Wait, let me retrace. `del a[1]` removes index 1 (value 2) -> `[1, 3, 2, 1]`. `remove(2)` removes the first 2 it finds, which is now at index 2 -> `[1, 3, 1]`. `pop()` removes the last element (1) -> `[1, 3]`. Correct answer is `[1, 3]`.

Problem 7easy

List over-allocation size growth

import sys
lst = []
for i in range(5):
    print(f'{len(lst)} {sys.getsizeof(lst)}')
    lst.append(i)
Expected Output:
0 56
1 88
2 88
3 88
4 88

Python lists use an over-allocation strategy to minimize the number of resizes. The initial size is 64 bytes. After appending elements, the list grows in chunks. The first resize happens at 5 elements, increasing the size to 128 bytes. Subsequent appends don't immediately trigger resizes until the allocated space is exhausted.

Problem 8medium

Clearing a List and Reference Tracking

a = [1, 2, 3]
b = a
a.clear()
print(b)
Expected Output: []

`a.clear()` removes all items from the list object in memory. Since `b` references the exact same list object, it also appears empty.

How to use this tool

Study the verified Lists Foundations & Memory Mechanics 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 Lists Foundations & Memory Mechanics
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 Lists Foundations & Memory Mechanics 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 / 60+30 XP

Extending a List with a String Iterable

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 / 60 Solved
main.pyCPython 3.12 (WASM)
1
2
3
a = [1, 2]
a.extend('34')
print(a)
Press Enter to submit
Match exact whitespace and capitalization

Frequently Asked Questions: Lists Foundations & Memory Mechanics

Why does [[0] * 3] * 3 cause unintended mutations across every row in a grid?

The repetition operator (*) duplicates object references, not object instances. The outer list receives three references pointing to the exact same inner list in heap memory. Modifying any nested element through one row mutates the shared underlying list.

How does CPython achieve amortized O(1) time complexity for list append operations?

CPython allocates extra buffer slots beyond the requested length using geometric growth. Appends fill pre-allocated empty pointer slots in O(1) time. Expensive reallocations and memory copies only occur periodically when all over-allocated slots are exhausted.

What is the memory and performance difference between list.sort() and sorted()?

list.sort() operates in place directly on the PyListObject pointer buffer, so it needs no extra list object, but Timsort still uses up to O(N/2) auxiliary space for its temporary run merges. In contrast, sorted() instantiates a brand new PyListObject and copies all elements, incurring O(N) additional memory allocation on top of that.