Dayrvia
Py

Python

Trace lists and dictionaries, then explore shallow copies and mutable default arguments.

Take the full quiz

Data structuresList slices

Taking a slice

List indices begin at zero. a[start:stop] builds a new list from start up to, but excluding, stop. len counts its elements.

Code example

a = [10, 20, 30, 40]
part = a[1:3]

Walkthrough

a[1:3] picks indices 1 and 2, producing [20, 30], which has two elements.

Loopsrange

Finding the end of a range

range(start, stop, step) advances from start by step and excludes stop. Initialise a running total outside the loop to keep the accumulation.

Code example

total = 0
for n in range(1, 6, 2):
    total += n

Walkthrough

n takes the values 1, 3 and 5. The running total becomes 1, 4 and 9.

Data structuresDictionaries

Counting with a dictionary

get(key, default) supplies a fallback when a key is missing. Reading with get alone does not insert a key.

Code example

counts = {}
counts["red"] = counts.get("red", 0) + 1

Walkthrough

The first read uses 0, then the assignment stores 1. Repeating the statement increases the stored count to 2.

Data structuresShallow copies

What a shallow copy shares

list.copy() creates a new outer list while preserving references to its elements. Mutating an inner list differs from replacing a slot in the outer list.

Code example

a = [[1], [2]]
b = a.copy()
b[0].append(9)
b[1] = [7]

Walkthrough

The first inner list is shared, so a[0] becomes [1, 9]. Replacing b[1] changes only the outer copy, leaving a[1] equal to [2].

FunctionsDefault arguments

Mutable default arguments

Default argument expressions are evaluated once when def executes. Mutating a default list can affect later calls. To get a fresh list for each omitted argument, use None and allocate inside the function.

Code example

def add_item(x, items=None):
    if items is None:
        items = []
    items.append(x)
    return items

Walkthrough

With no list argument, add_item(1) and add_item(2) return [1] and [2]. If a list is supplied, the function appends to that list.

Further reading