APDR

Functions, Tuples, and Lists

Algorithms, Programming, and Data Representation · Module 92313 · Chapter 7

This chapter gives programs structure. Functions package a piece of code under a name, take inputs, hand back a result and keep their own names apart from the rest of the program. Tuples and lists then hold many values under one name, and lists, because they can change, bring the chapter’s key idea: two names can point at the same object.

Start from memory

Try each question first. Mark it sure, unsure, or guessed.

  1. What does a function return when its body has no return statement?
  2. What is the difference between (5) and (5,)?
  3. After a = [1, 2] and b = a, what does b.append(3) do to a?
  4. What is the value of L.sort(), as opposed to sorted(L)?
  5. Can a function read a variable defined outside it? Can it rebind one?
Check the short answers
  1. None, the value that stands for “no value”. §7.3
  2. (5) is just the int 5 in brackets; (5,) is a tuple with one element. §7.6
  3. a becomes [1, 2, 3] too: both names point at the same list. §7.9
  4. L.sort() sorts L in place and returns None; sorted(L) returns a new sorted list and leaves L alone. §7.8
  5. It can read it. Assigning to that name inside the function makes a new local name instead, unless the name is declared global. §7.4

How to use this guide

Every example in this chapter is a short program. Read it, cover it, and write down what it prints before you run it; then trace it with one column per name. For lists, draw the list as a row of boxes and every name as an arrow to it: aliasing questions are answered by the arrows.

  1. Day 0: Try the cold start, then study §7.1–7.5; solve practice 2, 5, 6, 9, 10, 13.
  2. Day 1: Rebuild §7.1–7.5 from memory, then study §7.6–7.8; solve practice 1, 3, 7, 11, 12, 18.
  3. Day 3: Rebuild §7.6–7.8, then study §7.9–7.10 and draw the arrows for every example; solve practice 4, 8, 14, 15, 16, 17.
  4. About day 7: Do the derivation list cold, then practice 19–24 without notes.
  5. About day 14: Work both exam problems in 20 minutes each; answer the “Explain it” questions aloud.
  6. Before the exam: Tick only the self-check skills you can show cold; revisit the sections named in the answers you missed.

When stuck: draw frames and objects. Put each function call in its own box of names, put every list or tuple once on the right, and draw each name as an arrow to its object. A change through one arrow is seen through every arrow to the same object.

How the chapter fits together

Functions come first: what they are for, how to define and call one, what it hands back, and which names it can see. Tuples and lists then hold several values; the immutable tuple is simple, and the mutable list brings aliasing, cloning and the danger of changing a list while a loop walks through it.

Measure · structure a program

  • Decomposition and abstraction §7.1

    modules · black boxes

    Rests on: nothing earlier; it is the reason functions exist.

  • Defining and calling §7.2

    def name(params):

    Rests on: decomposition; a function is the unit you break a program into.

Define · what a call does

  • return versus print §7.3

    return value · None

    Rests on: calling; the value of a call is what its return hands back.

  • Scope §7.4

    one frame per call

    Rests on: calling; each call gets its own frame of names.

  • Functions as arguments §7.5

    f(g) · z()

    Rests on: return values; a function is an object you can pass and call later.

Derive · compound data

  • Tuples §7.6

    (q, r) = f(x, y)

    Rests on: return; a tuple lets a function return several values.

  • Lists and list operations §7.7–7.8

    L.append(x) · L[i] = v

    Rests on: tuples; a list is an ordered sequence that can change.

  • Aliasing and cloning §7.9

    b = a · b = a[:]

    Rests on: mutable lists and names that point at objects, also across calls.

  • Mutation during iteration §7.10

    for e in L[:]:

    Rests on: aliasing and cloning; loop over a copy, change the original.

QuestionTool
What does this call print, and what is its value?Run the body; the value is what return gives, else None (§7.2–7.3)
Which x does this line mean?Is x assigned anywhere in the function? Then it is local (§7.4)
What does this tuple or list expression give?Index and slice as for strings (§7.6–7.7)
Did this line change the list or make a new one?Methods mutate; +, slices and sorted make new lists (§7.8)
Does a change through one name show through another?Draw the arrows: same object or a copy? (§7.9)
Why did the loop skip an element?Track the loop’s hidden index while the list shrinks (§7.10)

7.1 Decomposition and abstraction

Programs so far were one long sequence of instructions; that works for small tasks and becomes unmanageable for larger ones.

In plain words: decomposition means splitting a program into self-contained pieces, modules, that each do one job and can be reused. Abstraction means using a piece as a black box: you know what goes in and what comes out, and you do not need, or want, to see how it works inside. A function provides both: its body is the module, and its name and description are all a caller needs.

The two ideas decomposition: break the code into self-contained, reusable modules abstraction: hide the details behind a specification Read it as: “split the work into pieces, and hide how each piece works”. This chapter decomposes with functions; classes, a few lectures later, are the second tool.

The lecture measures good programmers by the amount of functionality, not by the amount of code. More code is not a good thing in itself: every line must be kept correct. A function written once can be used many times but only has to be debugged once.

The specification of a function, its docstring, is what makes it a black box: it states what the input must be and what the function returns. Someone who calls is_even(7) reads “Returns True if i is even, otherwise False” and never needs to see the % inside.

Worked example · decompose a grade report

  1. Task: read scores, drop the invalid ones, and print the average. One block of code would mix all three jobs.
  2. Decompose: read_scores() returns a list, valid(scores) returns the valid ones, average(scores) returns a number.
  3. Abstract: each gets a docstring, so the main program reads print(average(valid(read_scores()))) without any inner detail.
  4. Check: each piece can be tested on its own, and fixing average fixes every place that calls it.

Trap: a function that also prints its result, or reads its own input, is harder to reuse. Let a function hand back a value and let the caller decide what to do with it (§7.3).

Near miss: copying a block of code to a second place looks like reuse, but now there are two copies to debug. Reuse means calling one function twice.

Recall check · answer without looking

  1. What is the difference between decomposition and abstraction?
  2. What does a docstring tell the caller of a function?
Check these answers
  1. Decomposition splits a program into self-contained modules; abstraction hides how each module works, so it can be used as a black box.
  2. What the inputs must be and what the function returns, so the caller can use it without reading the body.

7.2 Defining and calling functions

A function is the tool for decomposition; you need to know its parts and when its body actually runs.

In plain words: def writes a function down under a name, with parameters (zero or more input names in brackets), an optional docstring, and an indented body. Writing it down does not run it. The body runs only when the function is called (or invoked): its name followed by brackets holding the arguments, the values for the parameters.

Definition and call def name(p1, p2): docstring, then the body name(a1, a2): bind p1 to a1, p2 to a2, run the body Read it as: “define name with parameters p1 and p2; call name with arguments a1 and a2”. The number of arguments must match the number of parameters, or the call raises a TypeError.
def is_even(i):
    """
    Input: i, a positive int
    Returns True if i is even, otherwise False
    """
    print("We are inside is_even")
    return i % 2 == 0

is_even(3)

The lecture lists five characteristics: a function has a name, has parameters (0 or more), has a docstring (optional but recommended), has a body, and returns something. The docstring is a string in triple quotes as the first line of the body; Python ignores it when running, but it is the function’s specification.

Worked example · what runs when

  1. Python reads the def block and binds the name is_even to a function object. Nothing is printed yet.
  2. is_even(3) calls it: the parameter i is bound to 3, and the body starts.
  3. The body prints We are inside is_even, then evaluates 3 % 2 == 0 to False and returns it.
  4. Check: in a script nothing else appears, because the returned False is not printed; only the shell would echo it.

Trap: a file holding only a def block prints nothing when run. Defining is not calling.

Near miss: is_even without brackets looks like a call but is just the function object itself; only is_even(3) runs the body.

Recall check · answer without looking

  1. Name the five characteristics of a function given in the lecture.
  2. What happens when you call is_even() with no argument?
Check these answers
  1. A name, parameters (0 or more), a docstring (optional), a body, and a return value.
  2. A TypeError: is_even() is missing 1 required positional argument, i.

7.3 return versus print

The value a call gives back and the text a function shows on the screen are different things, and confusing them is the most common function bug.

In plain words: return ends the function and hands a value back to the caller, which can store it or compute with it. print only shows text on the console; the caller gets nothing from it. A function with no return hands back None, Python’s value for “no value”.

The value of a call return expr: the call’s value is expr no return reached: the call’s value is None Read it as: “a call is worth what its return statement hands back, and None if there is none”. Only one return runs per call; lines after it in the same block never run.
A call. The caller waits while the body runs, then continues with the returned value; with no return that value is None.
returnprint
Has meaning only inside a functionCan be used anywhere
Only one runs per callCan run many times in one call
Code after it in the block never runsCode after it runs as normal
Its value goes to the callerIts value goes to the console

The lecture’s second is_even has the body i%2 == 0 and no return. The comparison is worked out and thrown away, and the call returns None. So print(is_even(4)) prints None, not True.

Worked example · print inside, print outside

  1. def sq(x): print(x * x), then y = sq(3): the body prints 9.
  2. The body ends without a return, so sq(3) is None and y is bound to None.
  3. print(y) prints None. The output is 9, then None.
  4. Check: replace the body by return x * x and the output becomes just 9, from print(y).

Trap: double(3) + 1 with def double(x): print(2 * x) prints 6 and then fails: None + 1 raises a TypeError. Seeing the number on screen does not mean the caller got it.

Near miss: in the shell, a bare call such as is_even(3) shows False, which looks like printing. It is the shell echoing the returned value; in a script nothing appears.

Recall check · answer without looking

  1. What does print(is_even(4)) show when is_even has no return?
  2. A function body is return 1 followed by print("hi"). What does a call print?
Check these answers
  1. None: the comparison is computed but not returned.
  2. Nothing: return ends the call, so the print line never runs.

7.4 Scope

Functions use names too; you need to know which names a function sees and which ones it changes.

In plain words: every call gets a fresh frame (also called a scope or environment): a table that maps names to objects. The formal parameter, the name in the def line, is bound in that frame to the value of the actual parameter, the argument in the call. Names assigned inside the function live only in its frame and vanish when the call ends. A function can read a name from the main program, but assigning to a name inside a function always means a local name.

Which name is meant assigned anywhere in the function → local name in the call’s frame only read in the function → looked up in the main program’s frame Read it as: “a name the function assigns is its own; a name it only reads comes from outside”. Python decides this for the whole function before it runs, so reading a local name before its assignment raises an UnboundLocalError.
After the lecture’s z = f(x). The parameter x in f’s frame started as 3 and was rebound to 4; the main program’s x is still 3, and z holds the returned 4.
def f(x):
    x = x + 1
    print('in f(x): x =', x)
    return x

x = 3
z = f(x)

The lecture’s three scope examples each start with x = 5 and call a function with x as the argument. In f, the body assigns x = 1 and x += 1: that x is local, so f prints 2 and the main program’s x stays 5. In g, the body only reads x, so it picks up the main program’s 5. In h, the body is x += 1, which assigns, so x is local, but it is read before it has a value: UnboundLocalError.

Worked example · trace the lecture’s z = f(x)

  1. The main program binds x to 3, then calls f(x): a new frame opens, and the formal parameter x is bound to 3.
  2. In f’s frame, x = x + 1 rebinds the local x to 4; the line prints in f(x): x = 4.
  3. return x hands back 4, the frame disappears, and the main program binds z to 4.
  4. Check: the main program’s x was never touched, so print(x, z) would show 3 4.

Trap: x += 1 inside a function, with x defined only outside, does not change the outer x; it raises an UnboundLocalError, because the assignment makes x local for the whole function.

Near miss: naming the parameter x, like the outer variable, looks as if the function works on the outer x. It gets a copy of the outer name binding: rebinding the parameter never rebinds the caller’s name. (A list passed in is another story: §7.9.)

Recall check · answer without looking

  1. In the lecture’s g, where does the x in print(x) come from?
  2. Why does h fail, although x = 5 was set before the call?
  3. What is the difference between a formal and an actual parameter?
Check these answers
  1. From the main program’s frame, because g never assigns x.
  2. x += 1 assigns x, so x is local in h; the local x has no value when += reads it.
  3. The formal parameter is the name in the def line; the actual parameter is the value given in the call, which the formal one is bound to.

7.5 Functions as arguments

A function is an object like a number or a string, so it can be passed to another function and called there.

In plain words: the name of a function, written without brackets, refers to the function object. Passing it as an argument hands over the function itself, not its result. The receiving function can then call it with brackets whenever it likes.

Passing a function func_c(func_a): the parameter z is bound to the function func_a z() inside func_c: calls func_a Read it as: “give func_c the function func_a; func_c calls it as z()”. func_c(func_a()) would instead call func_a first and pass its result.
def func_a():
    print('inside func_a')

def func_b(y):
    print('inside func_b')
    return y

def func_c(z):
    print('inside func_c')
    return z()

print(func_a())
print(5 + func_b(2))
print(func_c(func_a))

func_a takes no parameters, func_b takes one, and func_c takes one that is itself a function. The three print lines show the output of each call followed by its value.

Worked example · the lecture’s three prints

  1. print(func_a()): the call prints inside func_a and returns None, so the next line is None.
  2. print(5 + func_b(2)): the call prints inside func_b and returns 2; then 5 + 2 is printed: 7.
  3. print(func_c(func_a)): func_c prints inside func_c, then z() calls func_a, which prints inside func_a and returns None; func_c returns that None, which is printed.
  4. Check: seven lines in all, 2 + 2 + 3, in the order the calls start: inside func_a, None, inside func_b, 7, inside func_c, inside func_a, None.

Trap: func_c(func_a()) calls func_a first and passes None; then z() tries to call None and raises a TypeError.

Near miss: print(func_a) looks like it calls func_a, but without brackets it prints the function object itself, something like <function func_a at 0x…>.

Recall check · answer without looking

  1. What is the difference between func_c(func_a) and func_c(func_a())?
  2. With def twice(f, x): return f(f(x)) and def inc(n): return n + 1, what is twice(inc, 0)?
Check these answers
  1. The first passes the function so func_c can call it; the second calls func_a first and passes its result, None.
  2. 2: inc(0) is 1, and inc(1) is 2.

7.6 Tuples

A function returns one value; a tuple bundles several values into one, so it can return them all.

In plain words: a tuple is an ordered sequence of elements, which may have different types, written in round brackets: (2, "fau", 3). It is immutable, like a string: you cannot change an element, only build a new tuple. Indexing, slicing, len and + work exactly as for strings.

Tuple operations t = (2, "fau", 3): t[0] → 2, len(t) → 3 t[1:2] → ("fau",), t[1:3] → ("fau", 3) (2, "fau", 3) + (5, 6) → (2, "fau", 3, 5, 6) Read it as: “index, slice, length and concatenation as for strings”. A slice of a tuple is a tuple. () is the empty tuple, and ("fau",) with its extra comma is a tuple with one element.
Packing and unpacking (x, y) = (y, x): swap two names return (q, r), then (quot, rem) = f(…) Read it as: “build a tuple on the right, then bind each name on the left to one element”. The right side is worked out completely before any name is bound, which is why the swap works.

t[1] = 4 raises a TypeError: a tuple does not support item assignment. To “change” one, build a new tuple, for example t = t[:1] + (4,) + t[2:].

The lecture’s get_data iterates over a tuple of (int, string) pairs. It starts with two empty tuples and grows them with nums = nums + (t[0],), adding a one-element tuple each round, and adds a word only if it is not in words yet. It returns (min_n, max_n, unique_words): the smallest and largest number and the count of distinct words.

Worked example · return two values

  1. quotient_and_remainder(4, 5) computes q = 4 // 5, which is 0, and r = 4 % 5, which is 4.
  2. return (q, r) hands back the single tuple (0, 4).
  3. (quot, rem) = (0, 4) unpacks it: quot is 0, rem is 4.
  4. Check: 5 · 0 + 4 = 4, so quotient and remainder rebuild the dividend.

Trap: the swap x = y then y = x loses a value: after the first line both names hold y’s value. Use a temporary name, or (x, y) = (y, x).

Near miss: (5) looks like a one-element tuple, but brackets alone only group: it is the int 5. The comma makes the tuple: (5,).

Recall check · answer without looking

  1. What are t[1:2] and t[1:3] for t = (2, "fau", 3)?
  2. Why does (x, y) = (y, x) swap correctly when x = y; y = x does not?
Check these answers
  1. ("fau",) and ("fau", 3), both tuples.
  2. The right side (y, x) is built from the old values before either name is rebound; the two-line version overwrites x before y reads it.

7.7 Lists

Many tasks need a sequence that grows, shrinks and changes; the list is that sequence.

In plain words: a list is an ordered sequence written in square brackets, [2, 1, 3], reached by index like a string or a tuple. Its elements are usually all of one type but may be mixed, and one element may itself be a list. Unlike a tuple, a list is mutable: L[1] = 5 changes the list in place, and it stays the same object.

Indexing a list L = [2, 'a', 4, [1, 2]]: len(L) → 4 L[0] → 2, L[2] + 1 → 5, L[3] → [1, 2] Read it as: “four elements, indexed 0 to 3; the last one is itself a list”. L[4] raises an IndexError, and an index may be any expression: with i = 2, L[i-1] is 'a'.
Changing an element L = [2, 1, 3], then L[1] = 5: L is [2, 5, 3] Read it as: “bind position 1 of the list to 5”. No new list is made; every name pointing at this list sees the change (§7.9).
total = 0
for i in range(len(L)):
    total += L[i]
print(total)

total = 0
for i in L:
    total += i
print(total)

Both loops sum the elements. The first walks the indices 0 to len(L) - 1, because range(n) goes from 0 to n − 1; the second walks the elements directly, as for char in s does for a string. (The slide writes print total, which is Python 2; see the slips list.)

Worked example · reach into a nested list

  1. With L = [2, 'a', 4, [1, 2]], L[3] is the inner list [1, 2].
  2. Index that list again: L[3][0] is 1 and L[3][1] is 2.
  3. len(L[3]) is 2, while len(L) is 4: the inner list counts as one element of the outer one.
  4. Check: L[3][2] would raise an IndexError, because the inner list has only indices 0 and 1.

Trap: in for i in L, the name i holds elements, not indices; writing L[i] inside that loop looks up the element’s value as a position.

Near miss: L[1] = 5 on a list works, so s[1] = "x" on a string or t[1] = 5 on a tuple looks fine too; both raise a TypeError, because strings and tuples are immutable.

Recall check · answer without looking

  1. What is len([1, [2, 3], 4])?
  2. Name one thing a list can do that a tuple cannot.
Check these answers
  1. 3: the inner list is one element.
  2. Change in place, for example L[0] = 9 or L.append(9).

7.8 List operations

Lists come with methods to add, remove, convert and sort; the key question for each is whether it changes the list or makes a new one.

In plain words: a method is a function that belongs to an object and is called with a dot: L.append(5). Everything in Python is an object with data and methods. Most list methods mutate the list, changing it in place, and return None. The operator +, slicing and sorted leave the list alone and return a new one.

Add L.append(x): add x at the end (mutates) L.extend(M): add every element of M at the end (mutates) L1 + L2: a new list; L1 and L2 unchanged Read it as: “append one item; extend by a whole list; plus builds a new list”. L.append([0, 6]) adds one element, the list [0, 6]; L.extend([0, 6]) adds two.
Remove del(L[i]): delete the element at index i L.pop(): remove the last element and return it L.remove(x): remove the first occurrence of x Read it as: “delete by position, pop from the end, remove by value”. All three mutate. remove raises a ValueError when x is not in the list.
Convert and sort list(s): every character of s as an element s.split(c): split s at each c; c.join(L): glue the strings of L with c L.sort(), L.reverse(): mutate, return None · sorted(L): a new sorted list Read it as: “list of characters; split at c, join with c; sort in place or sorted copy”. s.split() with no argument splits on spaces.

The lecture runs four removals in order on a list it does not show; its results fit L = [2, 1, 3, 6, 3, 7, 0]. L.remove(2) leaves [1, 3, 6, 3, 7, 0]; L.remove(3) takes only the first 3, leaving [1, 6, 3, 7, 0]; del(L[1]) deletes the 6, leaving [1, 3, 7, 0]; L.pop() returns 0 and leaves [1, 3, 7].

With s = "I<3 cs", list(s) is ['I', '<', '3', ' ', 'c', 's'] (the space is an element too) and s.split('<') is ['I', '3 cs']. With L = ['a', 'b', 'c'], ''.join(L) is "abc" and '_'.join(L) is "a_b_c".

Worked example · sort versus sorted

  1. L = [9, 6, 0, 3]; sorted(L) returns the new list [0, 3, 6, 9] and L is still [9, 6, 0, 3].
  2. L.sort() changes L itself to [0, 3, 6, 9] and returns None.
  3. L.reverse() then changes L to [9, 6, 3, 0].
  4. Check: M = L.sort() would bind M to None, exactly the lecture’s sortedwarm; assign the result of sorted, never of sort.

Trap: L = L.sort() throws the list away: L is now None. Call L.sort() on its own line.

Near miss: L.remove(3) sounds like “remove the element at index 3”, but it removes the value 3. Deleting by index is del(L[3]) or L.pop(3).

Recall check · answer without looking

  1. After L1 = [2, 1, 3], L3 = L1 + [4] and L1.extend([0, 6]), what are L1 and L3?
  2. What does "a b c".split() give?
  3. Which of append, +, pop, sorted and reverse mutate the list?
Check these answers
  1. L1 is [2, 1, 3, 0, 6]; L3 is [2, 1, 3, 4], a separate list made before the extend.
  2. ['a', 'b', 'c']: with no argument, runs of spaces count as one separator.
  3. append, pop and reverse; + and sorted make new lists.

7.9 Aliasing and cloning

Because lists can change, it matters whether two names point at one list or at two; this is where list bugs come from.

In plain words: a list is an object in memory, and a variable name only points at it. hot = warm does not copy the list; it makes a second name for the same list, an alias. Any change made through one name, such as hot.append('pink'), is a side effect visible through the other. To get an independent list, clone it: chill = cool[:] builds a new list with the same elements.

Alias or clone b = a: one list, two names b = a[:]: a new list holding the same elements Read it as: “b is another name for a; b is a copy of a”. After an alias, b.append(…) changes a too; after a clone it does not.
The lecture’s alias. warm and hot point at one list, so hot.append('pink') added the last box for both names.
The lecture’s clone. chill = cool[:] made a second list; chill.append('black') changed only that one.

Rebinding is different from mutating. a = a + [3] builds a new list and moves the name a to it; an alias b made earlier still points at the old list. a.append(3), and also a += [3], change the list itself, so b sees the change.

Lists can hold lists. In the lecture, brightcolors = [warm] and brightcolors.append(hot) put the two lists themselves, not copies, inside brightcolors. After hot.append('pink'), printing brightcolors shows [['yellow', 'orange'], ['red', 'pink']]: side effects reach through nesting too. A list passed to a function is aliased in the same way: the parameter points at the caller’s list.

Worked example · the lecture’s alias and clone

  1. warm = ['red', 'yellow', 'orange'], then hot = warm: one list, two arrows.
  2. hot.append('pink') mutates that list, so print(hot) and print(warm) both show ['red', 'yellow', 'orange', 'pink'].
  3. cool = ['blue', 'green', 'grey'], then chill = cool[:]: a second list; chill.append('black') changes only it.
  4. Check: print(chill) shows four colours, print(cool) still three; chill is cool is False while hot is warm is True.

Trap: a function that appends to its list parameter changes the caller’s list. If the caller needs its list unchanged, pass a clone, f(L[:]), or clone inside the function.

Near miss: after a = 1, b = a, b = 2, the lecture shows a is still 1, which looks like the opposite of aliasing. It is not: b = 2 rebinds b; it does not change the object. Ints cannot be changed at all, so only rebinding is possible.

Recall check · answer without looking

  1. After a = [1, 2], b = a, a = a + [3], what is b?
  2. Give two ways to clone a list.
Check these answers
  1. [1, 2]: a + [3] is a new list, and only a moved to it.
  2. b = a[:], as in the lecture, or b = list(a).

7.10 Mutation during iteration

Changing a list while a for loop walks through it silently skips elements; the fix is to loop over a clone.

In plain words: a for loop over a list keeps a hidden counter: the index of the next element to visit. Removing an element shifts everything after it one place left, but the counter still moves on by one, so the element that slid into the current position is never visited.

Loop over a copy, change the original for e in L1[:]: … L1.remove(e) Read it as: “walk a snapshot of L1, and remove from the real L1”. The clone’s length never changes, so every element is visited once.
def remove_dups(L1, L2):
    for e in L1:
        if e in L2:
            L1.remove(e)

L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6]
remove_dups(L1, L2)
The skipped element. Removing 1 shifts 2 into index 0, but the counter moves on to index 1 and finds 3.

The intended result is [3, 4]; the buggy loop leaves [2, 3, 4]. The lecture’s fix adds L1_copy = L1[:] and loops for e in L1_copy: while still removing from L1. Note that L1 inside the function is an alias of the caller’s L1 (§7.9), which is why the caller sees the removal at all.

Worked example · trace the hidden counter

  1. Counter 0: e is 1, which is in L2; L1.remove(1) leaves [2, 3, 4], and 2 now sits at index 0.
  2. Counter 1: e is 3, not in L2. Counter 2: e is 4, not in L2.
  3. Counter 3 equals the new length 3, so the loop ends after three rounds; 2 was never visited.
  4. Check with the copy: the loop visits 1, 2, 3, 4 from the unchanged clone, removes 1 and 2 from L1, and leaves [3, 4].

Trap: the bug does not always show. Removing even numbers from [1, 2, 3, 4] happens to give the right [1, 3], but from [2, 4, 5] it gives [4, 5]. Test with neighbouring elements that both match.

Near miss: L1_copy = L1 looks like a copy, but it is an alias (§7.9): the loop still walks the list that shrinks. The copy needs the slice, L1[:].

Recall check · answer without looking

  1. Why does the buggy remove_dups never see the element 2?
  2. Why does L1_copy = L1 not fix the bug?
Check these answers
  1. Removing 1 shifts 2 to index 0, but the loop’s counter moves on to index 1.
  2. It makes an alias, not a clone; the loop still walks the same list that is being shortened.

Formula map and units

RuleResult or meaning
def f(p): … f(a)p bound to a in a new frame; the body runs only at the call
value of a callthe return value, else None
name assigned in a functionlocal to each call; only read → taken from the main program
(), (x,), (x, y)tuples with 0, 1 and 2 elements; immutable
(a, b) = exprunpack; the right side is evaluated first
append, extend, remove, pop, del, sort, reverse, L[i] = v, L += Mmutate the list; all but pop return None
L1 + L2, L[:], sorted(L), list(L)new lists; the original is unchanged
b = a · b = a[:]alias (same object) · clone (new object)
for e in L:hidden counter 0, 1, 2, … checked against the current length

Check every answer: for a call, write down both what it prints and what it returns; for a list, ask whether each line mutated the object or rebound a name, and redraw the arrows; for a loop over a list that changes, track the counter and the current length together.

Derive it cold

  1. Trace x = 3, z = f(x) with the lecture’s f, drawing both frames, and state x and z at the end. §7.4
  2. Predict the output of the lecture’s f, g and h scope examples and explain each from the local-name rule. §7.4
  3. Write all output lines of the lecture’s three print calls with func_a, func_b and func_c. §7.3, §7.5
  4. Apply remove(2), remove(3), del(L[1]) and pop() in order to [2, 1, 3, 6, 3, 7, 0]. §7.8
  5. Draw names and objects for the lecture’s warm/hot, cool/chill and brightcolors programs. §7.9
  6. Trace the buggy and the fixed remove_dups with the loop counter, and explain the difference. §7.10

Explain it

  1. Why is code split into functions easier to debug than one long sequence of instructions?
  2. Why does a function that prints its result instead of returning it cause errors in the caller?
  3. Why does x += 1 inside a function fail when x exists only outside, while print(x) works?
  4. Why can a function return several values, if return hands back only one object?
  5. Why does hot.append('pink') change warm, while b = 2 after b = a does not change a?
  6. When must you loop over a clone of a list instead of the list itself?
Show model answers
  1. Each function is small, has a stated input and output, and can be tested alone; once it works, every call to it works, so a bug is found in one place. §7.1
  2. The caller receives None, not the number on screen, so any further use, such as result + 1, fails or computes with None. §7.3
  3. An assignment anywhere in the function makes the name local for the whole function, so x += 1 reads a local x that has no value yet. A name that is only read is looked up in the main program. §7.4
  4. It returns one tuple that holds them all, and the caller unpacks it into several names. §7.6
  5. append mutates the one list that both names point at. b = 2 only moves the name b to another object; nothing is mutated. §7.9
  6. When the loop body adds or removes elements of that list: the hidden counter does not adjust to the new positions, so elements are skipped or visited twice. §7.10

Mixed practice

Try all 24 problems before opening the answers. The order mixes every section on purpose, so you have to choose the method yourself. Predict each output on paper, then check it in a Python shell.

  1. With t = (4, "ab", 7), evaluate t[1:3] and t[2:3].
  2. def sq(x): print(x * x). What do y = sq(5) and then print(y) show?
  3. L = [3, 1, 2], then L.append(4) and L.extend([5]). What does print(L, len(L)) show?
  4. a = [1, 2], b = a, b[0] = 9. What is a?
  5. def f(): print(n), then n = 7 and f(). What is printed, and why is it not an error?
  6. Give two benefits of splitting a program into functions.
  7. With L = [2, 'a', 4, [1, 2]], evaluate L[3][0] and len(L[3]).
  8. L = [1, 2, 3], then for e in L: L.remove(e). What is L afterwards?
  9. A file contains only def greet(): print("hi"). What does running the file print?
  10. def twice(f, x): return f(f(x)) and def inc(n): return n + 1. What is twice(inc, 5)?
  11. L = [5, 3, 5, 1], then L.remove(5). What does print(L.pop(), L) show?
  12. With x = 1 and y = 2, what do x = y, y = x, print(x, y) show? Write a correct swap in one line.
  13. def f(x): with the body return x + 1 and then print("done"). What does f(1) print, and what is its value?
  14. c = [1, 2], d = c[:], d.append(3). What does print(c, d) show?
  15. x = 3 and def h(): x = x * 2. What happens when h() is called?
  16. With L = [4, 1, 3] and total = 0, the loop for i in range(len(L)): total += L[i] * i runs. What is total?
  17. L1 = [2, 4, 5], then for e in L1: with the body if e % 2 == 0: L1.remove(e). What is L1?
  18. Evaluate "a-b-c".split("-") and "+".join(["a", "b", "c"]).
  19. Write a function cube(n) with a docstring, and name each of the lecture’s five parts in it.
  20. What does (q, r) = quotient_and_remainder(17, 5) bind q and r to?
  21. warm = ["red"], bright = [warm], warm.append("pink"). What does print(bright) show?
  22. def double(x): print(2 * x). What happens on double(3) + 1?
  23. The function say returns the string "hi"; the function run(g) calls g and returns the result with "!" added. What are run(say) and run(say())?
  24. L = [9, 6, 0, 3], M = sorted(L), L.reverse(). What does print(L, M) show?
Show worked answers
  1. ('ab', 7) and (7,): slices of a tuple are tuples, and a one-element tuple prints with its comma. §7.6
  2. 25, then None: the body prints, but without a return the call’s value is None. §7.3
  3. [3, 1, 2, 4, 5] 5: append adds one element and extend adds each element of [5]. §7.8
  4. [9, 2]: b is an alias, so changing an element through b changes the one list. §7.9
  5. 7: f only reads n, so it looks it up in the main program, where n is bound by the time f is called. §7.4
  6. Code is written and debugged once and reused by calling it; the program stays organised, and each piece can be used as a black box through its docstring. §7.1
  7. 1 and 2: L[3] is the inner list [1, 2]. §7.7
  8. [2]: counter 0 removes 1 (list [2, 3]), counter 1 finds 3 and removes it (list [2]), counter 2 is past the end. §7.10
  9. Nothing: the file only defines the function and never calls it. §7.2
  10. 7: inc(5) is 6, then inc(6) is 7. §7.5
  11. 1 [3, 5]: remove(5) takes the first 5 only, leaving [3, 5, 1]; pop() returns 1 and removes it. §7.8
  12. 2 2: x = y overwrites 1 before it is saved. Correct: (x, y) = (y, x). §7.6
  13. Nothing, and its value is 2: return ends the call before the print line. §7.3
  14. [1, 2] [1, 2, 3]: c[:] is a clone, so append changes only d. §7.9
  15. An UnboundLocalError: the assignment makes x local in h, and the right side reads it before it has a value. §7.4
  16. 7: 4 · 0 + 1 · 1 + 3 · 2 = 0 + 1 + 6. §7.7
  17. [4, 5]: counter 0 removes 2, shifting 4 to index 0; counter 1 finds 5, which stays. The 4 is never checked. §7.10
  18. ['a', 'b', 'c'] and "a+b+c". §7.8
  19. def cube(n): gives the name cube and one parameter n; next, """Input: n, an int. Returns n cubed.""" is the docstring; return n ** 3 is the body and what it returns. §7.2
  20. q is 3 and r is 2, because 17 = 5 · 3 + 2. §7.6
  21. [['red', 'pink']]: bright holds the list warm itself, not a copy. §7.9
  22. It prints 6, then raises a TypeError: double(3) is None, and None + 1 is not defined. §7.3
  23. "hi!"; and a TypeError, because say() passes the string "hi", and g() tries to call a string. §7.5
  24. [3, 0, 6, 9] [0, 3, 6, 9]: sorted made a separate list before reverse mutated L. §7.8

Exam-style problems

1 · A bonus that leaks · 20 minutes

def add_bonus(scores, bonus):
    for i in range(len(scores)):
        scores[i] += bonus
    return scores

base = [50, 70, 90]
new = add_bonus(base, 5)
new.append(100)
print(base, len(base))
  1. What does the program print? Trace the list after each line of the main program.
  2. Explain with names and objects why base changed although the main program never assigns to it.
  3. Change add_bonus so that base stays [50, 70, 90] and new gets the bonus.
  4. Suppose the return line is deleted. What happens on new.append(100), and why?
Show the worked answer
  1. The loop adds 5 to each element: [55, 75, 95]. new then gets 100 appended to the same list, so the program prints [55, 75, 95, 100] 4. §7.7, §7.8
  2. The parameter scores points at the caller’s list, so scores[i] += bonus mutates it. The function returns that same list, so new is a third name for it, and new.append(100) changes it again. Only one list exists. §7.4, §7.9
  3. Clone first: result = scores[:], then add the bonus to result[i] in the loop and return result. Now new is a different list, and base is untouched. §7.9
  4. The call returns None, so new is None and new.append(100) raises an AttributeError: None has no method append. (The bonus was still added to base.) §7.3

2 · Counting with tuples · 20 minutes

def split_counts(pairs):
    names = []
    total = 0
    for p in pairs:
        if p[1] == 0:
            pairs.remove(p)
        else:
            names.append(p[0])
            total += p[1]
    return (names, total)

data = [("ann", 2), ("bob", 0), ("cy", 0), ("dee", 3)]
(n, t) = split_counts(data)
print(n, t, len(data))
  1. Trace the loop’s hidden counter and the list pairs, round by round. What is printed?
  2. The intention was to remove every pair with a count of 0. Which pair survives, and why?
  3. Fix the function with one change, and give the new output.
  4. Why is p[1] = 1 inside the loop an error, while pairs.remove(p) is allowed?
Show the worked answer
  1. Counter 0: ann, count 2, so names is ['ann'] and total 2. Counter 1: bob, count 0, removed; the list is now ann, cy, dee. Counter 2: dee, count 3, so names is ['ann', 'dee'] and total 5. Counter 3 equals the length 3: done. It prints ['ann', 'dee'] 5 3. §7.10, §7.6
  2. ("cy", 0) survives. Removing bob shifted cy into index 1, and the counter moved on to index 2, so cy was never tested. §7.10
  3. Loop over a clone: for p in pairs[:]:. Every pair is visited, both zero pairs are removed from data, and it prints ['ann', 'dee'] 5 2. §7.10, §7.9
  4. p is a tuple, which is immutable, so assigning to p[1] raises a TypeError. pairs is a list, which is mutable, so removing one of its elements is allowed. §7.6, §7.7

Slips in the notes

Each item was checked against the rendered slides and against Python 3. Slide numbers refer to “07_abstraction_functions_tupels_lists.pdf”.

  • Slide 12, docstring. The docstring of the version without return says “Does not return anything”. The function still returns a value, None, as the same slide then says; read it as “returns nothing useful” (§7.3).
  • Slide 15, error message. The h example is labelled “UnboundLocalError: local variable 'x' referenced before assignment”. That is the wording of Python up to 3.10; Python 3.11 and later say “cannot access local variable 'x' where it is not associated with a value”. The error type is the same (§7.4).
  • Slide 21, floor division. x // y is annotated “integer division”. It is floor division: it rounds down, so -7 // 2 is −4, and with a float operand the result is a float (Chapter 6, §6.2).
  • Slide 26, print. Both loops end with print total, which is Python 2 syntax; Python 3 raises a SyntaxError and needs print(total) (§7.7).
  • Slide 29, missing list. The four removals run “in order” on a list L that is never shown. The stated results fit L = [2, 1, 3, 6, 3, 7, 0], which this guide uses (§7.8).

Self-check

These are the chapter’s learning goals. Tick a skill only in a later session, at least one day after studying, when you can show it without notes.

Personal study guide based on the supplied “07_abstraction_functions_tupels_lists.pdf” (39 slides, lecture dated 3 May 2024; the slides credit MIT OpenCourseWare 6.0001), written in my own words; no lecture pages or figures are reproduced. Not an official FAU publication; check course details against the current notes. Made by Thanate Amornjiraporn (Focus).