Objectives: LO-7.1, LO-7.2, LO-7.3, LO-7.4
Prerequisites: Module 6
Time: about 5.5 hours: 2 for this reading, 2 for Lab 7, and 1.5 for the
practice
A list holds many values in order under one name: the scores in a class, the lines of a file,
the tasks on a to-do list. Module 6 used the lists that split returns. This module builds lists
and changes them, explains what happens when two names refer to the same list, shows a short way
to build one list from another, and introduces tuples, the fixed-size sequences Python uses for
records.
Making and reading lists¶
Write a list as values between square brackets, separated by commas:
scores = [72, 95, 88, 61]
names = ["Ada", "Grace", "Alan"]
empty = []
print(len(scores), scores[0], scores[-1], scores[1:3])4 72 61 [95, 88]Everything Module 6 showed for strings works the same way on lists: len, indices from 0,
negative indices, slices (which give a new list), and for loops over the items. A list can hold
values of different types, such as [1, "two", 3.0], but most lists hold one kind of thing.
inandnot inask whether a value is one of the items. Module 3’s rock, paper, scissors program could test a move withmove in ["rock", "paper", "scissors"]. On a list,incompares whole items:"pap" in ["rock", "paper"]isFalse, though"pap" in "paper"isTrue.listbuilds a list from any sequence:list("abc")is['a', 'b', 'c'], andlist(range(5))is[0, 1, 2, 3, 4].+joins two lists into a new one, and*repeats a list:[0] * 3is[0, 0, 0].sum,min, andmaxgive the total, the smallest item, and the largest.sum([])is 0, butminandmaxof an empty list stop with aValueError.An empty list counts as false, as Module 3 said, so
if scores:asks whetherscoreshas any items.
Worked example: a summary of scores¶
scores = [72, 95, 88, 61]
average = sum(scores) / len(scores)
print(f"{len(scores)} scores, average {average:.1f}, best {max(scores)}")4 scores, average 79.0, best 95Module 4 found a total with a loop and an accumulator. sum does the same job in one call, and
the code says what it does.
Changing a list¶
Strings can’t be changed, but lists can: they are mutable. You can replace a list’s items, add items, and remove them, and it stays the same list.
tasks = ["write report", "email Sam", "buy milk"]
tasks[1] = "email Priya"
tasks.append("water plants")
tasks.insert(0, "pay rent")
print(tasks)['pay rent', 'write report', 'email Priya', 'buy milk', 'water plants']items[i] = valuereplaces the item at indexi. It can’t add an item: an index past the end is anIndexError.append(x)addsxat the end.insert(i, x)putsxbefore the item at indexi, and moves the later items along one place.pop()removes the last item and returns it, andpop(i)removes and returns the item at indexi. Popping from an empty list stops withIndexError: pop from empty list.remove(x)removes the first item equal tox. If there is none, it stops withValueError: list.remove(x): x not in list.sort()puts the items in order, smallest first, or largest first withsort(reverse=True).
done = tasks.pop(0)
tasks.remove("buy milk")
tasks.sort()
print(done)
print(tasks)pay rent
['email Priya', 'water plants', 'write report']The methods that change a list return None, not the list. That is the opposite of string
methods, which return a new string because they can’t change the old one:
numbers = [3, 1, 2]
result = numbers.sort()
print(result, numbers)None [1, 2, 3]So numbers = numbers.sort() throws the list away and leaves numbers as None. To get a sorted
copy and keep the original, use sorted(numbers), which the last section explains.
Building a list in a loop¶
The accumulator pattern from Module 4 works with lists: start with the empty list, and append to it.
passed = []
for score in [72, 95, 88, 61]:
if score >= 70:
passed.append(score)
print(passed)[72, 95, 88]Changing a list while looping over it¶
Removing items from a list inside a for loop over the same list skips items:
numbers = [1, 2, 2, 3]
for number in numbers:
if number == 2:
numbers.remove(number)
print(numbers)[1, 2, 3]The loop keeps its place by index. When it removes the first 2, at index 1, every later item moves down one place, so the second 2 moves into index 1, which the loop has already passed. Build a new list of the items to keep instead, as the example before this one does.
Names, objects, and aliasing¶
Module 2 drew a variable as a name with an arrow to its value, and said that an assignment moves a name’s arrow but never changes a value. Numbers and strings can’t change, so for them that was the whole story. A list can change, so it matters how many arrows point to it:
a = [1, 2, 3]
b = a
b.append(4)
print(a)[1, 2, 3, 4]b = a doesn’t copy the list. It gives the same list a second name, so there is one list with two
arrows to it:
a ──┐
├──→ [1, 2, 3, 4]
b ──┘Two names for one object is called aliasing. Assignment in Python never copies a value; it only points a name at one.
is asks whether two names refer to the same object, and == asks whether two objects have equal
values:
c = [1, 2, 3, 4]
print(a == c, a is c, a is b)True False Truec is a different list that happens to have the same items. Use == to compare values; is is
for asking whether a value is None, as in if result is None:.
Changing an object, or moving a name¶
Two kinds of statement look alike but do different things.
A statement that changes the object, such as
b.append(5),b[0] = 9, orb.sort(), changes the one list, so every name that refers to it sees the change.An assignment to the name, such as
b = b + [5], builds a new list and moves onlyb’s arrow.astill refers to the old list.
a = [1, 2]
b = a
b = b + [3]
print(a, b)[1, 2] [1, 2, 3]+= catches people out: on a list, b += [3] changes the list in place, as append does, so a
sees the 3. On numbers and strings, which can’t change, += makes a new value, as in Module 2.
Lists passed to functions¶
A parameter is a name too. When you pass a list to a function, the parameter refers to the same list as the argument, so a function that changes the list changes the caller’s list:
def add_bonus(scores, bonus):
"""Add bonus to every score in the list scores, changing the list."""
for i in range(len(scores)):
scores[i] = scores[i] + bonus
results = [72, 95, 88]
add_bonus(results, 5)
print(results)[77, 100, 93]Assigning to the parameter only moves the local name, as Module 5 showed, and leaves the caller’s list alone:
def reset(scores):
scores = []
reset(results)
print(results)[77, 100, 93]A clear function does one of two things. Either it changes its argument and returns None, as
sort does, or it leaves its argument alone and returns a new value, as sorted does. Say which
in the docstring. A function that changes its argument and also returns it misleads callers who
think they got a copy.
Copies, shallow and deep¶
To get a separate list, copy it: a[:], list(a), and a.copy() each make a new list with the
same items.
original = [3, 1, 2]
duplicate = original.copy()
duplicate.sort()
print(original, duplicate)[3, 1, 2] [1, 2, 3]These copies are shallow: the new list refers to the same items as the old one. When the items
are numbers or strings, which can’t change, that makes no difference. When the items are lists,
the copy shares them. A list of lists is indexed twice: grid[0] is the first inner list, and
grid[0][1] is the second item of it.
grid = [[1, 2], [3, 4]]
duplicate = grid.copy()
duplicate[0].append(99)
duplicate.append([5, 6])
print(grid)
print(duplicate)[[1, 2, 99], [3, 4]]
[[1, 2, 99], [3, 4], [5, 6]]There are two outer lists but only three inner ones:
grid ──→ [ item 0, item 1 ]
duplicate ──→ [ item 0, item 1, item 2 ]
item 0 of both ──→ [1, 2, 99]
item 1 of both ──→ [3, 4]
item 2 of duplicate only ──→ [5, 6]duplicate[0].append(99) changed an inner list that both outer lists share, and
duplicate.append([5, 6]) changed only the outer copy. When you need the inner lists copied too,
copy.deepcopy(grid), from the standard library’s copy module, copies all the way down.
The repeated-row trap¶
[0] * 3 is safe, because it repeats a number, which can’t change. [[0] * 3] * 3 repeats one
inner list three times, so all three rows are the same list:
board = [[0] * 3] * 3
board[0][0] = 1
print(board)[[1, 0, 0], [1, 0, 0], [1, 0, 0]]The next section’s comprehensions build a new row each time: [[0] * 3 for row in range(3)].
Draw the names and objects before you run code like this, then check your drawing in Python Tutor, which draws every list as a box and every reference as an arrow.
List comprehensions¶
Many loops build one list from another:
squares = []
for n in range(1, 6):
squares.append(n * n)A list comprehension says the same thing in one expression:
squares = [n * n for n in range(1, 6)]
print(squares)[1, 4, 9, 16, 25]Read it as “n * n for each n in range(1, 6)”. An if at the end keeps only some items:
drinks = ["tea", "coffee", "milk", "hot chocolate"]
long_names = [drink.upper() for drink in drinks if len(drink) > 4]
print(long_names)['COFFEE', 'HOT CHOCOLATE']A comprehension and a loop translate into each other one part at a time:
result = [expression for name in sequence if condition]
result = []
for name in sequence:
if condition:
result.append(expression)A comprehension works on any sequence, strings included:
[c for c in "a1b2" if c.isdigit()]is['1', '2'], and"".jointurns such a list back into a string.The name in a comprehension exists only inside it. After
[n * n for n in range(5)],nisn’t defined, unless the code defined it before.Use a comprehension when a loop does nothing but build a list. Keep the loop when it does more, such as printing or updating other variables, or when the comprehension would need so many conditions that it is harder to read than the loop.
Tuples¶
A tuple is an ordered sequence, like a list, that can’t be changed. Write it with commas, usually inside parentheses:
point = (3, 4)
date = (2026, 12, 4)
print(point[0], date[1:], len(date))3 (12, 4) 3Indexing, slicing,
len,in, andforwork on tuples as on lists.A tuple has no methods that change it, and
point[0] = 5stops withTypeError: 'tuple' object does not support item assignment.The commas make a tuple, not the parentheses:
t = 3, 4is a tuple, but(5)is the number 5. A tuple of one item needs a comma,(5,), and()is the empty tuple.
Unpacking¶
Assigning a tuple to several names, separated by commas, unpacks it: each name gets one item.
x, y = point
year, month, day = date
print(x + y, month)7 12The counts must match. x, y = (1, 2, 3) stops with
ValueError: too many values to unpack (expected 2); Python 3.15 adds how many it got,
(expected 2, got 3). Unpacking works on any sequence, so first, second = "ab" works too.
Two uses come up often:
Swapping two variables:
a, b = b, a. The right side builds a tuple of the old values before either name moves.Returning several values from a function, as one tuple:
def min_max(values):
"""Return the smallest and the largest of values, as a tuple."""
return min(values), max(values)
low, high = min_max([72, 95, 88, 61])
print(low, high)61 95Lists of tuples: records¶
A tuple suits a record: a fixed number of fields, each with its own meaning, such as a name and
a score. A list suits a collection of things of the same kind that grows and shrinks. A list of
tuples is a table, and a for loop can unpack each row:
results = [("Ada", 92), ("Grace", 88), ("Alan", 95)]
for name, score in results:
print(f"{name:<6}{score:>4}")Ada 92
Grace 88
Alan 95:<6 writes the name on the left of six spaces, and :>4 writes the score on the right of four,
as Module 2’s receipt did.
| Use a tuple when | Use a list when |
|---|---|
| The number of items is fixed and each position means something: a point, a date, a record | The number of items changes, and every item is the same kind of thing |
| The value must not change, or must work as a dictionary key (Module 8) | You will add, remove, or sort items |
Looping with enumerate and zip¶
enumerate gives each item together with its index, in place of range(len(...)). start=1
counts from 1 instead of 0:
for position, name in enumerate(["Alan", "Ada", "Grace"], start=1):
print(position, name)1 Alan
2 Ada
3 Gracezip walks through several sequences side by side, and gives a tuple of their items at each step:
names = ["Ada", "Grace", "Alan"]
scores = [92, 88, 95]
for name, score in zip(names, scores):
print(name, score)
print(list(zip(names, scores)))Ada 92
Grace 88
Alan 95
[('Ada', 92), ('Grace', 88), ('Alan', 95)]zip stops at the end of the shortest sequence, without an error: list(zip("abc", [1, 2])) is
[('a', 1), ('b', 2)]. When the sequences must be the same length, zip(names, scores, strict=True) stops with a ValueError if they aren’t.
Sorting¶
sorted(sequence) returns a new list of the items in order, and leaves the sequence alone. The
list method sort() puts a list in order in place, and returns None. Both take reverse=True.
The order is the order of <: numbers by value, and strings by code point, so capitals come
before lowercase letters (Module 6). Items that < can’t compare, such as a number and a string,
stop with TypeError: '<' not supported between instances of 'str' and 'int'. Tuples compare
item by item, the way strings compare character by character, so a sorted list of tuples is in
order of the first item, and of the second where the first items are equal.
Sorting with a key¶
key= gives sorted a function to call on each item. It sorts the items by what the function
returns:
words = ["banana", "Cherry", "apple", "fig"]
print(sorted(words))
print(sorted(words, key=len))
print(sorted(words, key=str.lower))['Cherry', 'apple', 'banana', 'fig']
['fig', 'apple', 'banana', 'Cherry']
['apple', 'banana', 'Cherry', 'fig']key=lenpasses the function itself, without parentheses.sortedcalls it once for each item.str.loweris thelowermethod, taken from the typestr. Called with a string, it returns that string in lowercase, sokey=str.lowersorts while ignoring case."banana"and"Cherry"both have six letters, and they keep their original order. Python’s sort is stable: items with equal keys stay in the order they came in.
For records, write a function that returns the field to sort by:
def score_of(result):
"""Return the score from a (name, score) record."""
return result[1]
results = [("Ada", 92), ("Grace", 88), ("Alan", 95), ("Edsger", 88)]
print(sorted(results, key=score_of, reverse=True))
print(max(results, key=score_of))[('Alan', 95), ('Ada', 92), ('Grace', 88), ('Edsger', 88)]
('Alan', 95)min and max take a key too, and return the item with the smallest or largest key.
A lambda writes a short function in place, without a name: lambda result: result[1] is a
function that takes result and returns result[1]. So
sorted(results, key=lambda result: result[1], reverse=True) gives the same list. A lambda can
hold only one expression; give anything longer a name with def.
To sort by score, highest first, and by name where scores are equal, make the key a tuple:
key=lambda result: (-result[1], result[0]). Tuples compare item by item, and the minus sign
puts the highest score first while the names stay in alphabetical order:
[('Alan', 95), ('Ada', 92), ('Edsger', 88), ('Grace', 88)].
Common misconceptions¶
| Belief | What Python does | Example that breaks it |
|---|---|---|
b = a copies the list | It gives the same list a second name | After b.append(4), a has the 4 too |
sort() returns the sorted list | It sorts in place and returns None | numbers = numbers.sort() makes numbers None |
| A function can’t change its caller’s variables | It can change a list the caller passed | add_bonus(results, 5) changes results |
| Assigning to a parameter changes the caller’s list | It moves only the local name | reset(results) leaves results alone |
copy() copies everything inside a list | It is shallow: inner lists are shared | duplicate[0].append(99) changes grid[0] |
[[0] * 3] * 3 makes three rows | It makes one row, three times | Setting board[0][0] changes every row |
| Removing items while looping over a list is safe | Later items move into places the loop has passed | Removing the 2s from [1, 2, 2, 3] leaves a 2 |
in on a list finds part of an item | It compares whole items | "pap" in ["paper"] is False |
| Parentheses make a tuple | The comma does | (5) is 5; (5,) is a tuple |
Summary¶
A list is a mutable sequence: indices, slices,
len,in, andforwork as on strings, andappend,insert,pop,remove, andsortchange it. Methods that change a list returnNone.Assignment never copies. Two names, or a name and a parameter, can refer to one list, and a change made through either is seen through both. Assigning to a name moves only that name.
copy(),list(a), anda[:]make shallow copies, which share the items inside;copy.deepcopycopies all the way down.A list comprehension,
[expression for name in sequence if condition], builds a list in one expression, and translates to and from a loop that appends.A tuple is an immutable sequence for records of a fixed size. Unpacking assigns its items to names, and lets functions return several values.
enumeratepairs items with their indices,zippairs items from several sequences, andsorted,min, andmaxtake akeyfunction that says what to compare.
Self-check¶
Answer each question before you open its answer.
What does this print?
a = [1, 2, 3] b = a a.append(4) b = [0] print(a, b)Answer
[1, 2, 3, 4] [0].a.append(4)changes the list both names refer to; thenb = [0]movesbto a new list and leavesawhere it was.Rewrite this loop as a list comprehension.
lengths = [] for word in words: if word != "": lengths.append(len(word))Answer
lengths = [len(word) for word in words if word != ""]. Because an empty string counts as false,if wordworks too.Why does
numbers = numbers.sort()lose your list, and what should you write instead?Answer
sortchanges the list in place and returnsNone, and the assignment pointsnumbersat thatNone. Writenumbers.sort()on its own line, ornumbers = sorted(numbers).After
x, y, z = "abc", what isy? What doesx, y = "abc"do?Answer
yis"b": unpacking works on any sequence.x, y = "abc"stops withValueError: too many values to unpack (expected 2).Would you store each of these as a tuple or a list? (a) a student’s name, ID, and year of entry; (b) the scores one student earns over a term.
Answer
(a) A tuple: three fields of fixed number, each with its own meaning. (b) A list: scores of the same kind, added one at a time as the term goes on.
Further reading¶
The Python Tutorial, section 3.1.3, Lists, and sections 5.1, More on Lists (with 5.1.3, list comprehensions), 5.3, Tuples and Sequences, and 5.6, Looping Techniques. Every list method, and
enumerateandzip, in the language’s own words.Sorting Techniques, from the Python HOWTOs. Key functions, sorting by several fields, and why a stable sort makes that possible.
Ned Batchelder, Facts and Myths about Python Names and Values. The clearest explanation of names, references, and aliasing, with drawings like this module’s.
Python Tutor. Paste in any example from this module and step through it to see which names share a list.
Allen B. Downey, Think Python, 3rd edition, chapter 9, Lists, and chapter 11, Tuples. List methods, aliasing, and lists as arguments, then tuples,
zip,enumerate, andsorted.Al Sweigart, Automate the Boring Stuff with Python, 3rd edition, chapter 6, Lists. Lists, slicing, list methods, tuples, and references, with short programs that use each.