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.
- What does a function return when its body has no
returnstatement? - What is the difference between
(5)and(5,)? - After
a = [1, 2]andb = a, what doesb.append(3)do toa? - What is the value of
L.sort(), as opposed tosorted(L)? - Can a function read a variable defined outside it? Can it rebind one?
Check the short answers
None, the value that stands for “no value”. §7.3(5)is just the int 5 in brackets;(5,)is a tuple with one element. §7.6abecomes[1, 2, 3]too: both names point at the same list. §7.9L.sort()sortsLin place and returnsNone;sorted(L)returns a new sorted list and leavesLalone. §7.8- 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.
- Day 0: Try the cold start, then study §7.1–7.5; solve practice 2, 5, 6, 9, 10, 13.
- Day 1: Rebuild §7.1–7.5 from memory, then study §7.6–7.8; solve practice 1, 3, 7, 11, 12, 18.
- 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.
- About day 7: Do the derivation list cold, then practice 19–24 without notes.
- About day 14: Work both exam problems in 20 minutes each; answer the “Explain it” questions aloud.
- 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 boxesRests 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 · NoneRests on: calling; the value of a call is what its
returnhands back. -
Scope §7.4
one frame per callRests 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] = vRests 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.
| Question | Tool |
|---|---|
| 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 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
- Task: read scores, drop the invalid ones, and print the average. One block of code would mix all three jobs.
- Decompose:
read_scores()returns a list,valid(scores)returns the valid ones,average(scores)returns a number. - Abstract: each gets a docstring, so the main program reads
print(average(valid(read_scores())))without any inner detail. - Check: each piece can be tested on its own, and fixing
averagefixes 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
- What is the difference between decomposition and abstraction?
- What does a docstring tell the caller of a function?
Check these answers
- Decomposition splits a program into self-contained modules; abstraction hides how each module works, so it can be used as a black box.
- 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.
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
- Python reads the
defblock and binds the nameis_evento a function object. Nothing is printed yet. is_even(3)calls it: the parameteriis bound to 3, and the body starts.- The body prints
We are inside is_even, then evaluates3 % 2 == 0toFalseand returns it. - Check: in a script nothing else appears, because the returned
Falseis 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
- Name the five characteristics of a function given in the lecture.
- What happens when you call
is_even()with no argument?
Check these answers
- A name, parameters (0 or more), a docstring (optional), a body, and a return value.
- 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”.
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.
return that value is None.return | print |
|---|---|
| Has meaning only inside a function | Can be used anywhere |
| Only one runs per call | Can run many times in one call |
| Code after it in the block never runs | Code after it runs as normal |
| Its value goes to the caller | Its 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
def sq(x): print(x * x), theny = sq(3): the body prints9.- The body ends without a
return, sosq(3)isNoneandyis bound toNone. print(y)printsNone. The output is9, thenNone.- Check: replace the body by
return x * xand the output becomes just9, fromprint(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.
Watch return values and None in the lab
Recall check · answer without looking
- What does
print(is_even(4))show whenis_evenhas noreturn? - A function body is
return 1followed byprint("hi"). What does a call print?
Check these answers
None: the comparison is computed but not returned.- Nothing:
returnends the call, so theprintline 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.
UnboundLocalError.
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)
- The main program binds
xto 3, then callsf(x): a new frame opens, and the formal parameterxis bound to 3. - In
f’s frame,x = x + 1rebinds the localxto 4; the line printsin f(x): x = 4. return xhands back 4, the frame disappears, and the main program bindszto 4.- Check: the main program’s
xwas never touched, soprint(x, z)would show3 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.)
Step through frames and scope in the lab
Recall check · answer without looking
- In the lecture’s
g, where does thexinprint(x)come from? - Why does
hfail, althoughx = 5was set before the call? - What is the difference between a formal and an actual parameter?
Check these answers
- From the main program’s frame, because
gnever assignsx. x += 1assignsx, soxis local inh; the localxhas no value when+=reads it.- The formal parameter is the name in the
defline; 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.
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
print(func_a()): the call printsinside func_aand returnsNone, so the next line isNone.print(5 + func_b(2)): the call printsinside func_band returns 2; then 5 + 2 is printed:7.print(func_c(func_a)):func_cprintsinside func_c, thenz()callsfunc_a, which printsinside func_aand returnsNone;func_creturns thatNone, which is printed.- 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
- What is the difference between
func_c(func_a)andfunc_c(func_a())? - With
def twice(f, x): return f(f(x))anddef inc(n): return n + 1, what istwice(inc, 0)?
Check these answers
- The first passes the function so
func_ccan call it; the second callsfunc_afirst and passes its result,None. - 2:
inc(0)is 1, andinc(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.
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.
(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
quotient_and_remainder(4, 5)computesq = 4 // 5, which is 0, andr = 4 % 5, which is 4.return (q, r)hands back the single tuple(0, 4).(quot, rem) = (0, 4)unpacks it:quotis 0,remis 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,).
Try tuples, swaps and unpacking in the lab
Recall check · answer without looking
- What are
t[1:2]andt[1:3]fort = (2, "fau", 3)? - Why does
(x, y) = (y, x)swap correctly whenx = y; y = xdoes not?
Check these answers
("fau",)and("fau", 3), both tuples.- The right side
(y, x)is built from the old values before either name is rebound; the two-line version overwritesxbeforeyreads 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.
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'.
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
- With
L = [2, 'a', 4, [1, 2]],L[3]is the inner list[1, 2]. - Index that list again:
L[3][0]is 1 andL[3][1]is 2. len(L[3])is 2, whilelen(L)is 4: the inner list counts as one element of the outer one.- Check:
L[3][2]would raise anIndexError, 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
- What is
len([1, [2, 3], 4])? - Name one thing a list can do that a tuple cannot.
Check these answers
- 3: the inner list is one element.
- Change in place, for example
L[0] = 9orL.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.
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.
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.
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
L = [9, 6, 0, 3];sorted(L)returns the new list[0, 3, 6, 9]andLis still[9, 6, 0, 3].L.sort()changesLitself to[0, 3, 6, 9]and returnsNone.L.reverse()then changesLto[9, 6, 3, 0].- Check:
M = L.sort()would bindMtoNone, exactly the lecture’ssortedwarm; assign the result ofsorted, never ofsort.
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).
Run list operations step by step in the lab
Recall check · answer without looking
- After
L1 = [2, 1, 3],L3 = L1 + [4]andL1.extend([0, 6]), what areL1andL3? - What does
"a b c".split()give? - Which of
append,+,pop,sortedandreversemutate the list?
Check these answers
L1is[2, 1, 3, 0, 6];L3is[2, 1, 3, 4], a separate list made before the extend.['a', 'b', 'c']: with no argument, runs of spaces count as one separator.append,popandreverse;+andsortedmake 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.
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.
warm and hot point at one list, so hot.append('pink') added the last box for both names.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
warm = ['red', 'yellow', 'orange'], thenhot = warm: one list, two arrows.hot.append('pink')mutates that list, soprint(hot)andprint(warm)both show['red', 'yellow', 'orange', 'pink'].cool = ['blue', 'green', 'grey'], thenchill = cool[:]: a second list;chill.append('black')changes only it.- Check:
print(chill)shows four colours,print(cool)still three;chill is coolisFalsewhilehot is warmisTrue.
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.
Draw names and objects for aliasing in the lab
Recall check · answer without looking
- After
a = [1, 2],b = a,a = a + [3], what isb? - Give two ways to clone a list.
Check these answers
[1, 2]:a + [3]is a new list, and onlyamoved to it.b = a[:], as in the lecture, orb = 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.
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 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
- Counter 0:
eis 1, which is inL2;L1.remove(1)leaves[2, 3, 4], and 2 now sits at index 0. - Counter 1:
eis 3, not inL2. Counter 2:eis 4, not inL2. - Counter 3 equals the new length 3, so the loop ends after three rounds; 2 was never visited.
- 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[:].
Watch the loop counter skip an element in the lab
Recall check · answer without looking
- Why does the buggy
remove_dupsnever see the element 2? - Why does
L1_copy = L1not fix the bug?
Check these answers
- Removing 1 shifts 2 to index 0, but the loop’s counter moves on to index 1.
- It makes an alias, not a clone; the loop still walks the same list that is being shortened.
Formula map and units
| Rule | Result 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 call | the return value, else None |
| name assigned in a function | local to each call; only read → taken from the main program |
(), (x,), (x, y) | tuples with 0, 1 and 2 elements; immutable |
(a, b) = expr | unpack; the right side is evaluated first |
append, extend, remove, pop, del, sort, reverse, L[i] = v, L += M | mutate 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
- Trace
x = 3,z = f(x)with the lecture’sf, drawing both frames, and statexandzat the end. §7.4 - Predict the output of the lecture’s
f,gandhscope examples and explain each from the local-name rule. §7.4 - Write all output lines of the lecture’s three
printcalls withfunc_a,func_bandfunc_c. §7.3, §7.5 - Apply
remove(2),remove(3),del(L[1])andpop()in order to[2, 1, 3, 6, 3, 7, 0]. §7.8 - Draw names and objects for the lecture’s
warm/hot,cool/chillandbrightcolorsprograms. §7.9 - Trace the buggy and the fixed
remove_dupswith the loop counter, and explain the difference. §7.10
Explain it
- Why is code split into functions easier to debug than one long sequence of instructions?
- Why does a function that prints its result instead of returning it cause errors in the caller?
- Why does
x += 1inside a function fail whenxexists only outside, whileprint(x)works? - Why can a function return several values, if
returnhands back only one object? - Why does
hot.append('pink')changewarm, whileb = 2afterb = adoes not changea? - When must you loop over a clone of a list instead of the list itself?
Show model answers
- 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
- The caller receives
None, not the number on screen, so any further use, such asresult + 1, fails or computes withNone. §7.3 - An assignment anywhere in the function makes the name local for the whole function, so
x += 1reads a localxthat has no value yet. A name that is only read is looked up in the main program. §7.4 - It returns one tuple that holds them all, and the caller unpacks it into several names. §7.6
appendmutates the one list that both names point at.b = 2only moves the namebto another object; nothing is mutated. §7.9- 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.
- With
t = (4, "ab", 7), evaluatet[1:3]andt[2:3]. def sq(x): print(x * x). What doy = sq(5)and thenprint(y)show?L = [3, 1, 2], thenL.append(4)andL.extend([5]). What doesprint(L, len(L))show?a = [1, 2],b = a,b[0] = 9. What isa?def f(): print(n), thenn = 7andf(). What is printed, and why is it not an error?- Give two benefits of splitting a program into functions.
- With
L = [2, 'a', 4, [1, 2]], evaluateL[3][0]andlen(L[3]). L = [1, 2, 3], thenfor e in L: L.remove(e). What isLafterwards?- A file contains only
def greet(): print("hi"). What does running the file print? def twice(f, x): return f(f(x))anddef inc(n): return n + 1. What istwice(inc, 5)?L = [5, 3, 5, 1], thenL.remove(5). What doesprint(L.pop(), L)show?- With
x = 1andy = 2, what dox = y,y = x,print(x, y)show? Write a correct swap in one line. def f(x):with the bodyreturn x + 1and thenprint("done"). What doesf(1)print, and what is its value?c = [1, 2],d = c[:],d.append(3). What doesprint(c, d)show?x = 3anddef h(): x = x * 2. What happens whenh()is called?- With
L = [4, 1, 3]andtotal = 0, the loopfor i in range(len(L)): total += L[i] * iruns. What istotal? L1 = [2, 4, 5], thenfor e in L1:with the bodyif e % 2 == 0: L1.remove(e). What isL1?- Evaluate
"a-b-c".split("-")and"+".join(["a", "b", "c"]). - Write a function
cube(n)with a docstring, and name each of the lecture’s five parts in it. - What does
(q, r) = quotient_and_remainder(17, 5)bindqandrto? warm = ["red"],bright = [warm],warm.append("pink"). What doesprint(bright)show?def double(x): print(2 * x). What happens ondouble(3) + 1?- The function
sayreturns the string"hi"; the functionrun(g)callsgand returns the result with"!"added. What arerun(say)andrun(say())? L = [9, 6, 0, 3],M = sorted(L),L.reverse(). What doesprint(L, M)show?
Show worked answers
('ab', 7)and(7,): slices of a tuple are tuples, and a one-element tuple prints with its comma. §7.625, thenNone: the body prints, but without areturnthe call’s value isNone. §7.3[3, 1, 2, 4, 5] 5:appendadds one element andextendadds each element of[5]. §7.8[9, 2]:bis an alias, so changing an element throughbchanges the one list. §7.97:fonly readsn, so it looks it up in the main program, wherenis bound by the timefis called. §7.4- 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
- 1 and 2:
L[3]is the inner list[1, 2]. §7.7 [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- Nothing: the file only defines the function and never calls it. §7.2
- 7:
inc(5)is 6, theninc(6)is 7. §7.5 1 [3, 5]:remove(5)takes the first 5 only, leaving[3, 5, 1];pop()returns 1 and removes it. §7.82 2:x = yoverwrites 1 before it is saved. Correct:(x, y) = (y, x). §7.6- Nothing, and its value is 2:
returnends the call before theprintline. §7.3 [1, 2] [1, 2, 3]:c[:]is a clone, soappendchanges onlyd. §7.9- An
UnboundLocalError: the assignment makesxlocal inh, and the right side reads it before it has a value. §7.4 - 7: 4 · 0 + 1 · 1 + 3 · 2 = 0 + 1 + 6. §7.7
[4, 5]: counter 0 removes 2, shifting 4 to index 0; counter 1 finds 5, which stays. The 4 is never checked. §7.10['a', 'b', 'c']and"a+b+c". §7.8def cube(n):gives the namecubeand one parametern; next,"""Input: n, an int. Returns n cubed."""is the docstring;return n ** 3is the body and what it returns. §7.2qis 3 andris 2, because 17 = 5 · 3 + 2. §7.6[['red', 'pink']]:brightholds the listwarmitself, not a copy. §7.9- It prints 6, then raises a
TypeError:double(3)isNone, andNone + 1is not defined. §7.3 "hi!"; and aTypeError, becausesay()passes the string"hi", andg()tries to call a string. §7.5[3, 0, 6, 9] [0, 3, 6, 9]:sortedmade a separate list beforereversemutatedL. §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))
- What does the program print? Trace the list after each line of the main program.
- Explain with names and objects why
basechanged although the main program never assigns to it. - Change
add_bonusso thatbasestays[50, 70, 90]andnewgets the bonus. - Suppose the
returnline is deleted. What happens onnew.append(100), and why?
Show the worked answer
- The loop adds 5 to each element:
[55, 75, 95].newthen gets 100 appended to the same list, so the program prints[55, 75, 95, 100] 4. §7.7, §7.8 - The parameter
scorespoints at the caller’s list, soscores[i] += bonusmutates it. The function returns that same list, sonewis a third name for it, andnew.append(100)changes it again. Only one list exists. §7.4, §7.9 - Clone first:
result = scores[:], then add the bonus toresult[i]in the loop andreturn result. Nownewis a different list, andbaseis untouched. §7.9 - The call returns
None, sonewisNoneandnew.append(100)raises anAttributeError:Nonehas no methodappend. (The bonus was still added tobase.) §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))
- Trace the loop’s hidden counter and the list
pairs, round by round. What is printed? - The intention was to remove every pair with a count of 0. Which pair survives, and why?
- Fix the function with one change, and give the new output.
- Why is
p[1] = 1inside the loop an error, whilepairs.remove(p)is allowed?
Show the worked answer
- Counter 0: ann, count 2, so
namesis['ann']andtotal2. Counter 1: bob, count 0, removed; the list is now ann, cy, dee. Counter 2: dee, count 3, sonamesis['ann', 'dee']andtotal5. Counter 3 equals the length 3: done. It prints['ann', 'dee'] 5 3. §7.10, §7.6 ("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- Loop over a clone:
for p in pairs[:]:. Every pair is visited, both zero pairs are removed fromdata, and it prints['ann', 'dee'] 5 2. §7.10, §7.9 pis a tuple, which is immutable, so assigning top[1]raises aTypeError.pairsis 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
returnsays “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
hexample 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 // yis annotated “integer division”. It is floor division: it rounds down, so-7 // 2is −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 aSyntaxErrorand needsprint(total)(§7.7). - Slide 29, missing list. The four removals run “in order” on a list
Lthat is never shown. The stated results fitL = [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).