Python for data structures and recursion
Trace object contents separately from names. An assignment can rebind a name or change an existing container; these actions have different effects on aliases. Use Chapter 6 for recursion counts and return tracing, then apply the Python rules below.
11.1 Objects, names and references
Assignment binds a name to an object; it does not copy that object. Function parameters also receive object references. Changing a passed list is visible to its caller; rebinding the parameter is local. == compares values, while is tests whether two references identify the same object. Use is None for the missing-value sentinel; do not use is for numeric or string equality.
| Object operation | What remains shared? |
|---|---|
b = a | The entire object |
b = a.copy() or b = a[:], for a list | Nested elements; the outer list is new |
b = copy.deepcopy(a), for nested lists of numbers | Nested lists are copied too; internal sharing is preserved by the copying process |
Lists, dictionaries and sets are mutable. Integers, strings and tuples are immutable. A tuple can still contain a mutable list: its element reference stays fixed while the referenced list changes. For a list, += extends the existing object; a = a + other binds a to a new list. For integers and strings, augmented assignment rebinds the name to the result.
11.2 Lists, tuples, strings and slices
Past papers · DA 2024–2026 (3 papers): 2 questions, 3 marks
A Python list is a resizable array, not a linked list. Strings are sequences of Unicode characters; a one-character selection is still a string. A singleton tuple needs a comma, as in (7,).
For a sequence of length n, index -1 selects its last element; valid negative indices extend to -n. An out-of-range single index raises IndexError. A slice a[start:stop:step] excludes stop, clips bounds and may be empty. Its step must be nonzero. Omitted bounds depend on direction: a[::-1] reverses the sequence; an explicit -1 stop is normalised as an index and is not equivalent to an omitted stop.
| Operation | Result or effect |
|---|---|
a + b, a * k | Concatenation, repetition; list results have a new outer list |
a.append(x) | Add one element, even if x is a list |
a.extend(items) | Add each item from the iterable |
a.insert(i, x), a.pop(i) | Insert before position; remove and return position |
a.remove(x) | Remove the first equal value; absent value raises ValueError |
a.sort(), a.reverse() | Change the list and return None |
sorted(items) | Return a new sorted list |
a[i:j] = items | Replace a slice; list length may change |
x in a, len(a) | Membership, length |
A list slice is shallow. For an extended slice assignment with step other than one, replacement length must match the selected length. Strings and tuples do not permit item assignment. List/string/tuple comparisons are lexicographic when corresponding elements are comparable.
Use append and final-element pop() for a stack. For a queue, collections.deque supports append and popleft; removing a Python list's first element shifts the remainder.
A for loop iterates over items. range(start, stop, step) excludes stop; its step is nonzero. enumerate supplies index/item pairs; zip pairs corresponding items and by default stops at the shortest input. Comprehension clauses run in written nesting order, applying each filter where it appears. break exits the nearest loop; continue skips to its next iteration. A loop's else runs when the loop finishes without break. Separate if statements can both execute; an if/elif chain selects at most one arm. Indentation determines the suite.
11.3 Sets, dictionaries and iteration
Past papers · DA 2024–2026 (3 papers): 1 question, 2 marks
Sets contain distinct hashable elements. Dictionaries associate hashable keys with values. Lists and dictionaries cannot be keys; a tuple is hashable only when all its elements are hashable. {} is an empty dictionary; use set() for an empty set.
| Expression | Meaning |
|---|---|
A & B, A | B | Intersection, union |
A - B, A ^ B | Difference, symmetric difference |
A <= B, A < B | Subset, proper subset |
x in D | Key membership, not value membership |
D[k] = v | Insert a key or replace its existing value |
D.get(k, default) | Value if present; otherwise the supplied default, without insertion |
D.keys(), D.values(), D.items() | Views of keys, values, key/value pairs |
Dictionary iteration preserves insertion order; replacing a value does not move its key. A set has no promised iteration order. Do not change a dictionary's or set's size while iterating over it. For multiple assignment, evaluate the entire right side before assigning targets, so swaps need no temporary name.
Hash tables (chaining, open addressing, probe counts): see Algorithms.
11.4 Functions, scope and shared call state
Past papers · DA 2024–2026 (3 papers): 2 questions, 3 marks
A function without an executed value-returning return yields None. Arguments may be positional or named; *args collects extra positional arguments in a tuple and **kwargs extra named arguments in a dictionary. A default expression is evaluated when the def executes, not on each call. A mutable default therefore persists across calls to that function object. Use a None default and construct a fresh list inside the function when each call needs separate storage.
For ordinary nested functions, name lookup follows local, enclosing-function, global-module, then built-in scopes (LEGB). Assignment makes a name local throughout the function unless declared otherwise; reading that local before binding raises UnboundLocalError. global selects the module binding. nonlocal selects an existing enclosing-function binding. Mutating an enclosing list through its name needs no nonlocal; rebinding that name does.
A closure keeps access to its enclosing bindings after the outer call returns. Separate outer calls create separate enclosing state. Closures look up the current binding when called; they do not automatically freeze a loop variable's earlier value.
11.5 Integer arithmetic and Boolean evaluation
Python integers have arbitrary precision, limited by memory rather than a fixed signed word. Large-integer arithmetic is not constant cost in the number of bits. / performs true division and normally produces a float for integer operands; // is floor division, including for negative values. Floating results need not be exact. The following identities concern integers only.
** denotes exponentiation and groups from the right; exponentiation binds more tightly than a unary minus on its left. Parenthesise a negative base. ^ is bitwise exclusive-or. Comparison chains test adjacent pairs and evaluate the middle expression once.
False values include None, numeric zero and empty built-in containers. not returns a Boolean. x and y returns x if it is false, otherwise evaluates and returns y. x or y returns x if it is true, otherwise evaluates and returns y. Thus and/or return operands, not necessarily Booleans. Relevant precedence from higher to lower is arithmetic, comparisons, not, and, or.
Last-minute recall
- Draw names and objects separately; assignment does not copy.
- A shallow copy shares nested objects.
- A slice excludes its stop; omitted negative-step bounds are special.
appendadds one object;extenditerates over its argument.- Dictionary membership tests keys; set iteration has no promised order.
- Evaluate all right-hand expressions before a multiple assignment.
- Defaults belong to the function object; locals belong to each call.
- Closures retain bindings; separate outer calls create separate state.
- Apply Chapter 6's recursion method with Python's shared-object rules.
- Floor division and remainder use the divisor's sign convention.
- Short-circuit Boolean operators return the selected operand.