Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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.

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 95

Module 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']
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 True

c 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 = [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)

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) 3

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 12

The 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:

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 95

Lists 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 whenUse a list when
The number of items is fixed and each position means something: a point, a date, a recordThe 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 Grace

zip 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']

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

BeliefWhat Python doesExample that breaks it
b = a copies the listIt gives the same list a second nameAfter b.append(4), a has the 4 too
sort() returns the sorted listIt sorts in place and returns Nonenumbers = numbers.sort() makes numbers None
A function can’t change its caller’s variablesIt can change a list the caller passedadd_bonus(results, 5) changes results
Assigning to a parameter changes the caller’s listIt moves only the local namereset(results) leaves results alone
copy() copies everything inside a listIt is shallow: inner lists are sharedduplicate[0].append(99) changes grid[0]
[[0] * 3] * 3 makes three rowsIt makes one row, three timesSetting board[0][0] changes every row
Removing items while looping over a list is safeLater items move into places the loop has passedRemoving the 2s from [1, 2, 2, 3] leaves a 2
in on a list finds part of an itemIt compares whole items"pap" in ["paper"] is False
Parentheses make a tupleThe comma does(5) is 5; (5,) is a tuple

Summary

Self-check

Answer each question before you open its answer.

  1. 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; then b = [0] moves b to a new list and leaves a where it was.

  2. 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 word works too.

  3. Why does numbers = numbers.sort() lose your list, and what should you write instead?

    Answer

    sort changes the list in place and returns None, and the assignment points numbers at that None. Write numbers.sort() on its own line, or numbers = sorted(numbers).

  4. After x, y, z = "abc", what is y? What does x, y = "abc" do?

    Answer

    y is "b": unpacking works on any sequence. x, y = "abc" stops with ValueError: too many values to unpack (expected 2).

  5. 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