Weeks
Intro to PythonWeek 6 · Lists and Tuples
Week 6 Notes

Python,
Week 6

Lists and tuples: notation and properties, list operations and methods, aliasing versus copying, comparing lists, lists as function parameters, and tuple immutability, operations, methods and advantages.

8 chapters29 worked examples~29 min read
ListsList methodsAliasingCopyingTuples

Chapters

  1. 01Lists: Notation, Properties, + and *Parts 1-2
  2. 02List MethodsPart 3
  3. 03Aliasing and CopyingParts 4-5
  4. 04Comparing Lists and Passing Them to FunctionsParts 6-7
  5. 05Tuples: Notation, Indexing and ImmutabilityParts 8-9
  6. 06Changing Tuples, Methods and AdvantagesParts 10-11
  7. 07Try It YourselfPractice zone
  8. 08Week 6 Summary SheetAll parts
01
Lists

Lists: Notation, Properties, + and *

Square brackets, the properties of a list, indexing, and the + and * operators.

A list is Python's general-purpose, ordered collection. Week 4 introduced lists and their basic methods; this week goes further, into every method, aliasing and copying, comparisons, lists in functions, and tuples.

1.1Notation and properties

List

A list is written with square brackets [ ] and created either with the list() function or by simply writing l = []. Its items can be of any type, they keep their order, and the list can be changed after it is made.

PropertyValue
Notation[ ]
Creationlist() or l = []
MutabilityMutable: we can change the order of items or reassign an item
Types of elements storedAny
Order of elementsOrdered
Duplicate elementsAllowed
SortingPossible
Python
l1 = []
l2 = list()
l3 = [10, "ten", 10.0, True, 10]
print(l1, l2)
print(l3)
print(len(l3))
Output
[] []
[10, 'ten', 10.0, True, 10]
5

One list can hold an int, a string, a float and a bool together, and 10 appears twice: duplicates are allowed. list() also converts another sequence into a list (extra):

Python
print(list("abc"))
print(list(range(4)))
print(list((1, 2, 3)))
Output
['a', 'b', 'c']
[0, 1, 2, 3]
[1, 2, 3]

1.2Indexing, slicing and changing an item

l =[1020304050]0-51-42-33-24-1indexnegative index
Figure 1. Positions from the front (0, 1, ...) and from the back (-1, -2, ...)
Python
l = [10, 20, 30, 40, 50]
print(l[0], l[-1])
print(l[1:3])
l[0] = 99
print(l)
Output
10 50
[20, 30]
[99, 20, 30, 40, 50]

Indexing and slicing work exactly as for strings (Week 3). The difference is the last line: l[0] = 99 changes the list itself, which a string never allows. That is what mutable means.

1.3List operations: + and *

The + operator appends one list to another, and * replicates a list a given number of times.

Python
l1 = [1, 2, 3]
l2 = [4, 5]
l3 = l1 + l2
l4 = l1 * 3
print(l3)
print(l4)
Output
[1, 2, 3, 4, 5]
[1, 2, 3, 1, 2, 3, 1, 2, 3]
l1 + l2: joins[12345]l1 * 3: repeats[123123123]
Figure 2. l1 + l2 joins the lists; l1 * 3 repeats l1 three times

Both build a new list; l1 and l2 are unchanged. Two details worth knowing (extra):

Python
l = [1, 2, 3]
l = l + 4
Error
TypeError: can only concatenate list (not "int") to list

+ joins a list with a list only; to add one item write l + [4] or use append. Repeating zero times gives an empty list, and [0] * 5 is a quick way to make five zeros:

Python
print([1, 2] * 0)
print([0] * 5)
Output
[]
[0, 0, 0, 0, 0]

1.4A trap with * and nested lists (extra)

* repeats the references it is given. With a list inside a list that matters:

Python
grid = [[0] * 3] * 3
grid[0][0] = 1
print(grid)
Output
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

All three rows changed, because [[0] * 3] * 3 holds the same inner list three times (aliasing, Chapter 3). Building each row separately avoids it:

Python
grid = [[0] * 3 for i in range(3)]
grid[0][0] = 1
print(grid)
Output
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]

1.5Exam tips and common mistakes

Exam tips
  • For + and *, work out the new list first, then answer length or index questions.
  • Count nested lists as one item each.
Common mistakes
  • Writing l + 4 instead of l + [4].
  • Building a grid with [[0] * n] * n.
  • Thinking + changes the original list.

Practice questions (graded-assignment style)

Q1Length and index

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
l = [2, 4] * 2 + [6]
print(len(l), l[-2])
1
5 6
2
5 4
3
4 4
4
3 6
Solution
Idea

Do * before +.

Python
l = [2, 4] * 2 + [6]
print(len(l), l[-2])
Output
5 4
  • [2, 4] * 2 is [2, 4, 2, 4]; adding [6] gives 5 items.
  • l[-2] is the 4 before the 6.
  • Answer: option 2.
Q2Replacing with a list

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
l = [1, 2, 3]
l[1] = [7, 8]
print(l, len(l))
1
[1, 7, 8, 3] 4
2
[1, 7, 3] 3
3
[1, [7, 8], 3] 3
4
An error
Solution
Idea

An item can be any value, including a list.

Python
l = [1, 2, 3]
l[1] = [7, 8]
print(l, len(l))
Output
[1, [7, 8], 3] 3
  • l[1] becomes the list [7, 8]; the length stays 3.
  • Answer: option 3.
Q3Repeated rows

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
rows = [[0] * 2] * 2
rows[1][1] = 5
print(rows)
1
[[0, 5], [0, 5]]
2
[[0, 0], [0, 5]]
3
[[0, 5], [0, 0]]
4
An error
Solution
Idea

* repeats the same inner list.

Python
rows = [[0] * 2] * 2
rows[1][1] = 5
print(rows)
Output
[[0, 5], [0, 5]]
  • Both rows are the same list, so the change shows in both.
  • Answer: option 1.
Q4list() of a string

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
l = list("CT")
print(l + ["!"])
1
['CT', '!']
2
['CT!']
3
CT!
4
['C', 'T', '!']
Solution
Idea

list() splits a string into characters.

Python
l = list("CT")
print(l + ["!"])
Output
['C', 'T', '!']
  • list("CT") is ['C', 'T'].
  • Answer: option 4.
Revision overview
List[ ] or list()
Ordered, mutable
Any types, duplicates
Indexingl[0], l[-1]
l[1:3]
l[0] = 99 works
ListsParts 1-2
+ and *+ joins two lists
* repeats
Both make new lists
Trap[[0] * 3] * 3
Same inner list
Build rows separately
Revision: what a list is and the + and * operators
Next · ListsList Methods
02
Lists

List Methods

append, extend, insert, pop, remove, count, index, sort, reverse, copy and clear, each run.

The main list methods are append(), extend(), insert(), pop(), remove(), count(), index(), sort(), reverse(), copy() and clear().

2.1The walkthrough from the source

Python
l = [1, 2, 3]
l.append(4)              # adds 4 at the end
print(l)                 # [1, 2, 3, 4]
x = [4, 5]
l.extend(x)              # merges x into l
print(l)                 # [1, 2, 3, 4, 4, 5]
y = [8, 4, 9, 6]
y.sort()
print(y)                 # [4, 6, 8, 9]
y.pop()                  # deletes last element -> [4, 6, 8]
y.pop(0)                 # deletes element at index 0 -> [6, 8]
l.insert(4, 0)           # inserts 0 at index 4
z = l.count(4)           # counts 4 in the list
l.reverse()
n = l.index(3)           # gives index of element 3
l1 = y.copy()            # copies list y to l1
l.clear()                # empties the list
Output
[1, 2, 3, 4]
[1, 2, 3, 4, 4, 5]
[4, 6, 8, 9]
Correction. The source comments l.insert(4, 0) as "inserts '4' at index 0". It is the other way round: insert(index, value) puts the value 0 at index 4. The comment above is corrected. The block only prints three times; the run below prints every step.
Python
l = [1, 2, 3]
l.append(4)
print("append:", l)
l.extend([4, 5])
print("extend:", l)
y = [8, 4, 9, 6]
y.sort()
print("sort:", y)
print("pop() removed", y.pop(), "->", y)
print("pop(0) removed", y.pop(0), "->", y)
l.insert(4, 0)
print("insert(4, 0):", l)
print("count(4):", l.count(4))
l.reverse()
print("reverse:", l)
print("index(3):", l.index(3))
l1 = y.copy()
print("copy:", l1)
l.clear()
print("clear:", l)
Output
append: [1, 2, 3, 4]
extend: [1, 2, 3, 4, 4, 5]
sort: [4, 6, 8, 9]
pop() removed 9 -> [4, 6, 8]
pop(0) removed 4 -> [6, 8]
insert(4, 0): [1, 2, 3, 4, 0, 4, 5]
count(4): 2
reverse: [5, 4, 0, 4, 3, 2, 1]
index(3): 4
copy: [6, 8]
clear: []
MethodWhat it doesReturnsChanges the list?
append(x)adds x at the endNoneyes
extend(seq)adds every item of seqNoneyes
insert(i, x)puts x at index iNoneyes
pop() / pop(i)removes the last item / the item at ithe removed itemyes
remove(x)removes the first xNoneyes
count(x)counts xan intno
index(x)finds the first xits indexno
sort()sorts in placeNoneyes
reverse()reverses in placeNoneyes
copy()makes a shallow copya new listno
clear()removes everythingNoneyes

2.2append and extend

Python
a = [1, 2]
a.append([3, 4])
print(a, len(a))
b = [1, 2]
b.extend([3, 4])
print(b, len(b))
Output
[1, 2, [3, 4]] 3
[1, 2, 3, 4] 4

append adds its argument as one item, even a whole list (length 3). extend adds each item of the list separately (length 4), like + but changing the list in place.

2.3insert(index, value)

before: l = [1, 2, 3, 4, 4, 5][123445]012345l.insert(4, 0): put 0 at index 4after[1234045]insert(index, value): the index comes first
Figure 3. l.insert(4, 0): the first argument is the position, the second the value
Python
l = [10, 20, 30]
l.insert(0, 5)
print(l)
l.insert(2, 15)
print(l)
l.insert(100, 99)
print(l)
Output
[5, 10, 20, 30]
[5, 10, 15, 20, 30]
[5, 10, 15, 20, 30, 99]

An index past the end simply appends (extra): insert(100, 99) put 99 last without an error.

2.4pop and remove

Python
l = [10, 20, 30, 40]
last = l.pop()
print(last, l)
first = l.pop(0)
print(first, l)
Output
40 [10, 20, 30]
10 [20, 30]

pop removes by position and gives back the removed item. remove removes by value, only the first match:

Python
l = [3, 1, 3, 2]
l.remove(3)
print(l)
Output
[1, 3, 2]

Both complain when there is nothing to remove (extra):

Python
l = []
l.pop()
Error
IndexError: pop from empty list
Python
l = [3, 1, 2]
l.remove(9)
Error
ValueError: list.remove(x): x not in list

2.5count and index

Python
l = [5, 7, 5, 9, 5]
print(l.count(5))
print(l.index(5))
print(l.index(9))
Output
3
0
3

index gives the position of the first match. A value that is not there raises an error rather than returning -1 (extra):

Python
l = [5, 7, 9]
print(l.index(4))
Error
ValueError: list.index(x): x not in list

2.6sort, sorted and reverse

Python
l = [3, 1, 2]
l.sort()
print(l)
l.sort(reverse=True)
print(l)
words = ["pear", "Apple", "fig"]
words.sort()
print(words)
Output
[1, 2, 3]
[3, 2, 1]
['Apple', 'fig', 'pear']

sort(reverse=True) sorts in descending order. Strings sort by character codes, so capital letters come before small ones: "Apple" before "fig" (extra). The classic trap: sort() returns None.

Python
l = [3, 1, 2]
l = l.sort()
print(l)
Output
None

To keep the original and get a sorted copy, use the built-in sorted() (extra):

Python
l = [3, 1, 2]
s = sorted(l)
print(s, l)
Output
[1, 2, 3] [3, 1, 2]
Python
l = [1, 2, 3]
print(l[::-1], l)
l.reverse()
print(l)
Output
[3, 2, 1] [1, 2, 3]
[3, 2, 1]

l[::-1] makes a reversed copy; reverse() reverses the list itself. Sorting is possible on lists: sort() works in place, while a fresh copy can be made with copy(), list() or slicing [:].

2.7Exam tips and common mistakes

Exam tips
  • Ask for each method: does it change the list, and what does it return?
  • Trace the list after every line.
Common mistakes
  • Reading insert(i, x) as value first.
  • Writing l = l.sort(), which leaves None.
  • Expecting remove to delete every copy of a value.
  • Using append to join two lists.

Practice questions (graded-assignment style)

Q1append and extend

Numerical Answer Type (NAT).

What does the program print?

Python
l = [1, 2, 3]
l.append([4, 5])
l.extend([6, 7])
print(len(l))
Solution
Idea

append adds one item, extend adds each.

Python
l = [1, 2, 3]
l.append([4, 5])
l.extend([6, 7])
print(len(l))
Output
6
  • 3 items, +1 (the list [4, 5]), +2 (6 and 7).
  • Answer: 6
Q2pop then insert

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
l = [10, 20, 30, 40]
x = l.pop(1)
l.insert(0, x)
print(l)
1
[10, 20, 30, 40]
2
[20, 30, 40]
3
[20, 10, 30, 40]
4
[10, 30, 40, 20]
Solution
Idea

pop(1) removes and returns 20.

Python
l = [10, 20, 30, 40]
x = l.pop(1)
l.insert(0, x)
print(l)
Output
[20, 10, 30, 40]
  • After pop: [10, 30, 40]; insert 20 at index 0.
  • Answer: option 3.
Q3remove, count, index

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
l = [4, 1, 4, 2, 4]
l.remove(4)
print(l.count(4), l.index(4))
1
3 0
2
2 1
3
2 0
4
0 1
Solution
Idea

remove deletes only the first 4.

Python
l = [4, 1, 4, 2, 4]
l.remove(4)
print(l.count(4), l.index(4))
Output
2 1
  • The list becomes [1, 4, 2, 4]: two 4s, the first at index 1.
  • Answer: option 2.
Q4sort returns

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
l = [3, 1, 2]
r = l.sort()
print(r, l)
1
[1, 2, 3] [1, 2, 3]
2
[1, 2, 3] [3, 1, 2]
3
None [3, 1, 2]
4
None [1, 2, 3]
Solution
Idea

sort works in place.

Python
l = [3, 1, 2]
r = l.sort()
print(r, l)
Output
None [1, 2, 3]
  • r is None; l is sorted.
  • Answer: option 4.
Q5sorted keeps the original

Numerical Answer Type (NAT).

What does the program print?

Python
l = [5, 3, 8]
s = sorted(l, reverse=True)
print(s[0] - l[0])
Solution
Idea

sorted returns a new list.

Python
l = [5, 3, 8]
s = sorted(l, reverse=True)
print(s[0] - l[0])
Output
3
  • s = [8, 5, 3] while l stays [5, 3, 8]: 8 − 5.
  • Answer: 3
Revision overview
Addingappend(x): one item
extend(seq): each item
insert(i, x): index first
Removingpop(): by position, returns it
remove(x): first match
clear(): everything
List methodsPart 3
Findingcount(x)
index(x): first match
Missing: ValueError
Orderingsort(): in place, None
sorted(): new list
reverse() vs [::-1]
Revision: what each list method does and returns
Next · ListsAliasing and Copying
03
Lists

Aliasing and Copying

Two names for one list, three ways to copy, and why the copies are shallow.

3.1Aliasing

If a refers to a list and we assign b = a, then both variables refer to the same list object. This association of a variable with an object is called a reference. An object with more than one reference is said to be aliased.

Python
a = [1, 2, 3]
b = a
print(b is a)
c = a.copy()
print(c is a)
Output
True
False
b = a: one list, two namesab[123]b is a → Truec = a.copy(): two listsac[123][123]c is a → False
Figure 4. b = a gives one list two names; a.copy() makes a second list

Since a list is mutable, a change made through one alias affects the other:

Python
a = [1, 2, 3, 4]
b = a
b[0] = 17
print(a)
Output
[17, 2, 3, 4]
Key idea

Although sometimes useful, aliasing is error-prone. It is generally safer to avoid aliasing when working with mutable objects: copy the list instead.

3.2Copying a list: three ways

Python
l = [1, 2, 3]
l1 = l.copy()
l2 = list(l)
l3 = l[:]
l1[0] = 100
l2.append(4)
l3.clear()
print(l)
print(l1, l2, l3)
Output
[1, 2, 3]
[100, 2, 3] [1, 2, 3, 4] []

l.copy(), list(l) and l[:] each make a new list. Any change made in l1, l2 or l3 afterwards does not affect the original l, as the run shows.

3.3Shallow copies (extra)

All three ways copy only the outer list. If the items are themselves lists, the copy holds references to the same inner lists:

Python
a = [[1, 2], [3, 4]]
b = a.copy()
b[0][0] = 99
print(a)
print(b is a, b[0] is a[0])
Output
[[99, 2], [3, 4]]
False True
ab = a.copy()outer lists: separate[99, 2][3, 4]inner lists: sharedb[0][0] = 99 changes a too
Figure 5. a.copy() makes a new outer list, but both share the inner lists

For a fully independent copy of nested lists, use copy.deepcopy:

Python
import copy
a = [[1, 2], [3, 4]]
b = copy.deepcopy(a)
b[0][0] = 99
print(a)
print(b)
Output
[[1, 2], [3, 4]]
[[99, 2], [3, 4]]

3.4== against is

Python
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b, a is b)
Output
True False

== asks "same contents?"; is asks "the same object?". Two lists built separately can be equal without being the same object.

Link to Computational Thinking Week 8 (extra). The CT pseudocode treats myl2 = l2 as a copy. In Python, myl2 = l2 is an alias; write myl2 = l2[:] or l2.copy() for a real copy.

3.5Exam tips and common mistakes

Exam tips
  • Draw names and arrows: which names point to which list?
  • After a copy, ask whether the items are themselves lists.
Common mistakes
  • Thinking b = a copies the list.
  • Assuming copy() also copies inner lists.
  • Using is to compare contents.

Practice questions (graded-assignment style)

Q1Alias and copy

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
a = [1, 2, 3]
b = a
b.append(4)
c = a[:]
c.append(5)
print(len(a), len(c))
1
4 5
2
3 5
3
4 4
4
3 4
Solution
Idea

b is an alias, c is a copy.

Python
a = [1, 2, 3]
b = a
b.append(4)
c = a[:]
c.append(5)
print(len(a), len(c))
Output
4 5
  • b.append(4) changes a (length 4). c was copied after that, then got 5 (length 5).
  • Answer: option 1.
Q2Shallow copy

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
a = [[1], [2]]
b = list(a)
b[0].append(9)
b[1] = [7]
print(a)
1
[[1], [2]]
2
[[1, 9], [7]]
3
[[1, 9], [2]]
4
[[1], [7]]
Solution
Idea

list(a) copies the outer list only.

Python
a = [[1], [2]]
b = list(a)
b[0].append(9)
b[1] = [7]
print(a)
Output
[[1, 9], [2]]
  • b[0] is the same inner list as a[0], so 9 shows in a.
  • Replacing b[1] changes only b.
  • Answer: option 3.
Q3== and is

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
a = [1, 2]
b = [1, 2]
c = a
print(a == b, a is b, a is c)
1
True True True
2
True False True
3
False False True
4
True False False
Solution
Idea

Contents against identity.

Python
a = [1, 2]
b = [1, 2]
c = a
print(a == b, a is b, a is c)
Output
True False True
  • a and b are equal but different objects; c is a.
  • Answer: option 2.
Revision overview
Aliasingb = a
Same object
Change shows in both
AliasingParts 4-5
Copyingcopy(), list(), [:]
Shallow: inner lists shared
deepcopy for nested
Checking== same contents
is same object
Revision: references, aliases and copies
Next · ListsComparing Lists and Passing Them to Functions
04
Lists

Comparing Lists and Passing Them to Functions

Lexicographic comparison, and why a function can change the caller's list.

4.1Comparing two lists

Lists can be compared with == (equal contents), and with < / >, which compare lexicographically: element by element, from left to right.

Python
l1 = [1, 2, 3]
l2 = [1, 2, 3]
l3 = [1, 3, 2]
l4 = [4]
print(l1 == l2)
print(l2 == l3)
print(l2 < l3)
print(l4 > l1)
print([1, 2] < [2, 1])
print([1] < [1, 2, 3])
print([] < [1])
Output
True
False
True
True
True
True
True
l2l311equal, go on232 < 3 decides: True32not looked at
Figure 6. l2 < l3: the first elements are equal, the second ones decide
  1. Compare the first elements. If they differ, that decides the answer.
  2. If they are equal, move to the next pair, and so on.
  3. If one list runs out first (it is a prefix of the other), the shorter list is smaller: [1] < [1, 2, 3], [] < [1].

This is how words are ordered in a dictionary, which is where "lexicographic" comes from. [1, 2] < [2, 1] is True because 1 < 2 at the first position; the rest is never looked at. Likewise [4] > [1, 2, 3].

4.2Mixed types (extra)

Python
print(["apple"] < ["banana"])
print([2, "a"] < [3])
Output
True
True

Strings compare like words, and a mixed list is fine as long as the answer is decided before two unlike items meet. If an int has to be compared with a string, Python refuses:

Python
print([1, 2] < [1, "a"])
Error
TypeError: '<' not supported between instances of 'int' and 'str'

4.3Passing lists as parameters to functions

Since lists are mutable, changes made to a list inside a function are also visible outside it. The source calls this call by reference (unlike int or strings, which behave like call by value).

Python
def add(x):
    x.append(1)
    return x

x = [5]
print(add(x))
print(x)
Output
[5, 1]
[5, 1]
caller's xparameter x[51]x.append(1) changes the shared listx = [0] inside would only move the local name
Figure 7. The caller's x and the parameter x refer to the same list
More exactly (extra). Python always passes a reference to the object. What happens next depends on the object and on what the function does with it:
  • Changing the object through the parameter (append, x[0] = ...) is visible to the caller, as above.
  • Assigning a new object to the parameter only moves the local name; the caller keeps its list:
Python
def reset(lst):
    lst = [0]
    return lst

data = [5, 6]
print(reset(data))
print(data)
Output
[0]
[5, 6]

An int or a string cannot be changed in place, so a function can only rebind its parameter, and the caller never sees a change. That is why they look like call by value:

Python
def bump(n):
    n = n + 1
    return n

k = 5
print(bump(k))
print(k)
Output
6
5

To leave the caller's list untouched, copy inside the function and return the copy:

Python
def add_safe(x):
    y = x.copy()
    y.append(1)
    return y

x = [5]
print(add_safe(x))
print(x)
Output
[5, 1]
[5]
Link to Computational Thinking Week 8 (extra). The same question, "can this call change my data?", is the side-effect topic of CT Week 8. add has a side effect on its argument; add_safe has none.

4.4Exam tips and common mistakes

Exam tips
  • For comparisons, find the first position where the lists differ.
  • Inside a function, check whether the parameter is changed or rebound.
Common mistakes
  • Comparing lists by length: [4] > [1, 2, 3] is True.
  • Thinking a rebinding inside a function changes the caller.
  • Comparing an int with a string inside lists.

Practice questions (graded-assignment style)

Q1First difference

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
print([2, 1, 9] < [2, 3])
1
True
2
False
3
An error
4
None
Solution
Idea

Compare position by position.

Python
print([2, 1, 9] < [2, 3])
Output
True
  • 2 equals 2; then 1 < 3 decides. The 9 is never compared.
  • Answer: option 1.
Q2Prefix

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
print([1, 2, 3] > [1, 2])
1
True
2
False
3
An error
4
None
Solution
Idea

A prefix is smaller.

Python
print([1, 2, 3] > [1, 2])
Output
True
  • [1, 2] is a prefix of [1, 2, 3], so the longer list is greater.
  • Answer: option 1.
Q3Change, then rebind

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
def f(lst):
    lst.append(0)
    lst = [9]
    lst.append(1)

data = [5]
f(data)
print(data)
1
[5]
2
[5, 0]
3
[9, 1]
4
[5, 0, 1]
Solution
Idea

Only changes before the rebinding reach the caller.

Python
def f(lst):
    lst.append(0)
    lst = [9]
    lst.append(1)

data = [5]
f(data)
print(data)
Output
[5, 0]
  • append(0) changes data; after lst = [9] the function works on a new list.
  • Answer: option 2.
Q4int and list parameters

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
def g(n, lst):
    n = n * 2
    lst[0] = lst[0] * 2

a = 3
b = [3]
g(a, b)
print(a, b)
1
6 [6]
2
3 [3]
3
3 [6]
4
6 [3]
Solution
Idea

An int is rebound; the list is changed in place.

Python
def g(n, lst):
    n = n * 2
    lst[0] = lst[0] * 2

a = 3
b = [3]
g(a, b)
print(a, b)
Output
3 [6]
  • a stays 3; b[0] is doubled to 6.
  • Answer: option 3.
Revision overview
Comparing== same contents
< > element by element
First difference decides
Edge casesPrefix is smaller
[] < [1]
int vs str: TypeError
Compare and passParts 6-7
ParametersReference to the object
Change in place: caller sees it
Rebind: caller does not
SafeCopy inside
Return the copy
Revision: comparing lists and passing them to functions
Next · TuplesTuples: Notation, Indexing and Immutability
05
Tuples

Tuples: Notation, Indexing and Immutability

Round brackets, the single-item comma, indexing and slicing, and why t[0] = ... fails.

5.1Notation and properties

Tuple

A tuple is a sequence of values, much like a list, but tuples are immutable. Values are indexed by integers and can be of any type.

PropertyValue
Notation( )
Creationtuple() or t = (10,)
MutabilityImmutable
Types of elements storedAny
Order of elementsOrdered
Duplicate elementsAllowed
OperationsIndexing, slicing, iteration
SortingNot possible in place
Methodscount(), index()

Tuples are also comparable (like lists, element by element) and hashable when all their items are (Chapter 6). Enclosing a tuple in parentheses is common, but not strictly necessary:

Python
t = 1, 2, 3, 4
print(t, type(t))
t = (1, 2, 3, 4)
print(t)
e = ()
print(e, len(e))
Output
(1, 2, 3, 4) <class 'tuple'>
(1, 2, 3, 4)
() 0

5.2One item needs a comma

To create a single-element tuple you must include the final comma: t1 = ('a',) is a tuple, but t2 = ('a') is just a string in brackets.

Python
t1 = ('a',)
t2 = ('a')
print(type(t1), type(t2))
Output
<class 'tuple'> <class 'str'>
Key idea

It is the comma that makes a tuple, not the parentheses. (7) is just the int 7.

If the argument to tuple() is a sequence (string, list, tuple), the result is a tuple with the elements of that sequence:

Python
t = tuple('hello')
print(t)
print(tuple([1, 2]))
Output
('h', 'e', 'l', 'l', 'o')
(1, 2)

5.3Indexing, slicing and immutability

Python
t = ('a', 'b', 'c')
print(t[0])
t = (1, 2, 3, 4)
print(t[1:3])
print(t[-1])
Output
a
(2, 3)
4

Indexing and slicing work exactly as for lists; a slice of a tuple is a tuple. But we cannot modify the elements of a tuple once it has been made:

Python
t = ('a', 'b', 'c')
t[0] = 'A'
Error
TypeError: 'tuple' object does not support item assignment

Tuples have no adding or removing methods either (extra):

Python
t = (1, 2)
t.append(3)
Error
AttributeError: 'tuple' object has no attribute 'append'
Python versions. Error messages here come from Python 3.14. Older versions word some of them a little differently, but the error type (TypeError, AttributeError) is the same.

5.4Exam tips and common mistakes

Exam tips
  • Look for the comma to decide whether something is a tuple.
  • Any attempt to change a slot of a tuple is a TypeError.
Common mistakes
  • Writing (5) for a one-item tuple.
  • Expecting append or sort on a tuple.

Practice questions (graded-assignment style)

Q1The comma

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
t = (7)
u = (7,)
print(type(t) == type(u))
1
True
2
False
3
An error
4
None
Solution
Idea

Which one is a tuple?

Python
t = (7)
u = (7,)
print(type(t) == type(u))
Output
False
  • t is the int 7, u is a tuple.
  • Answer: option 2.
Q2tuple() and +

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
t = tuple("abc") + ("d",)
print(len(t), t[1:3])
1
3 ('b', 'c')
2
4 ('a', 'b')
3
4 ('b', 'c')
4
An error
Solution
Idea

tuple("abc") has three items.

Python
t = tuple("abc") + ("d",)
print(len(t), t[1:3])
Output
4 ('b', 'c')
  • The tuple is ('a', 'b', 'c', 'd'); its slice 1:3 is ('b', 'c').
  • Answer: option 3.
Q3Reversed slice

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
t = (1, 2, 3)
print(t[::-1])
1
[3, 2, 1]
2
(1, 2, 3)
3
An error
4
(3, 2, 1)
Solution
Idea

A slice of a tuple is a tuple.

Python
t = (1, 2, 3)
print(t[::-1])
Output
(3, 2, 1)
  • [::-1] reverses it.
  • Answer: option 4.
Revision overview
Tuple( ) or tuple()
Ordered, immutable
Any types, duplicates
One item('a',) is a tuple
('a') is a str
TuplesParts 8-9
Accesst[0], t[-1]
t[1:3] is a tuple
Immutablet[0] = ...: TypeError
No append, no sort
Revision: tuple notation and immutability
Next · TuplesChanging Tuples, Methods and Advantages
06
Tuples

Changing Tuples, Methods and Advantages

Nested lists, + and *, count and index, and when to choose a tuple.

6.1A list inside a tuple

Tuples are immutable, but if an element is itself mutable (like a list), its nested items can be changed. A tuple variable can also be reassigned entirely.

Python
my_tuple = (4, 2, 3, [6, 5])
my_tuple[3][0] = 9
print(my_tuple)
my_tuple = ('g', 'a', 'g', 'n', 'e', 'e', 't')
print(my_tuple)
Output
(4, 2, 3, [9, 5])
('g', 'a', 'g', 'n', 'e', 'e', 't')
my_tuple: 4 fixed slots(423•)[95]the list itself can changeslot 3 holds a listreplacing a slot: TypeError
Figure 8. The slot that holds the list is fixed; the list in it can change
Python
my_tuple = (4, 2, 3, [6, 5])
my_tuple[1] = 9
Error
TypeError: 'tuple' object does not support item assignment

The tuple still holds the same list object in slot 3; only that list's contents changed. Replacing what a slot holds is what immutability forbids. Assigning a whole new tuple to my_tuple is allowed: the name simply refers to a different tuple.

6.2+ and *

The + operator concatenates two tuples; * repeats the elements a given number of times. Both make a new tuple.

Python
print((1, 2, 3) + (4, 5, 6))
print((1, 2) * 3)
Output
(1, 2, 3, 4, 5, 6)
(1, 2, 1, 2, 1, 2)

6.3Tuple methods

Python
t1 = ('a', 'p', 'p', 'l', 'e')
print(t1.count('p'))
print(t1.index('l'))
Output
2
3

Only two methods: count() and index(), both read-only. The built-in sorted() still works on a tuple, but returns a list (extra):

Python
t = (3, 1, 2)
print(sorted(t))
print(tuple(sorted(t)))
Output
[1, 2, 3]
(1, 2, 3)
Python
t = (3, 1, 2)
t.sort()
Error
AttributeError: 'tuple' object has no attribute 'sort'

6.4Advantages of tuples over lists

  • Tuples are generally used for heterogeneous (different) data types, lists for homogeneous (similar) data types.
  • Since tuples are immutable, iterating through a tuple is slightly faster than through a list.
  • A tuple made only of immutable elements can be used as a dictionary key. Lists cannot.
  • If your data does not change, a tuple guarantees it stays write-protected.
Python
marks = {}
marks[("Asha", "Maths")] = 91
marks[("Asha", "Physics")] = 84
print(marks[("Asha", "Maths")])
Output
91
Hashable only if every item is (extra). The source calls tuples hashable. That holds only when all their items are hashable: a tuple holding a list cannot be a key.
Python
d = {}
d[(1, [2, 3])] = "x"
Error
TypeError: cannot use 'tuple' as a dict key (unhashable type: 'list')
Python
d = {}
d[[1, 2]] = "x"
Error
TypeError: cannot use 'list' as a dict key (unhashable type: 'list')

6.5Packing and unpacking (extra)

Python
a, b = 1, 2
a, b = b, a
print(a, b)
Output
2 1

1, 2 packs a tuple and a, b = ... unpacks it; a, b = b, a swaps two variables in one line.

6.6Exam tips and common mistakes

Exam tips
  • Changing an item of a list inside a tuple is allowed; replacing a slot is not.
  • For dictionary keys, check every item of the tuple.
Common mistakes
  • Calling a tuple with a list in it "fully immutable".
  • Expecting sorted(t) to return a tuple.
  • Using a list as a dictionary key.

Practice questions (graded-assignment style)

Q1Nested list

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
t = (1, [2, 3], 4)
t[1].append(5)
print(len(t), len(t[1]))
1
4 3
2
3 3
3
3 2
4
An error
Solution
Idea

The list inside can grow; the tuple cannot.

Python
t = (1, [2, 3], 4)
t[1].append(5)
print(len(t), len(t[1]))
Output
3 3
  • The tuple still has 3 slots; the inner list now has 3 items.
  • Answer: option 2.
Q2count and index

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
t = (0, 1) * 2 + (2,)
print(t.count(1), t.index(2))
1
2 4
2
2 2
3
1 4
4
4 2
Solution
Idea

Build the tuple first.

Python
t = (0, 1) * 2 + (2,)
print(t.count(1), t.index(2))
Output
2 4
  • (0, 1, 0, 1, 2): two 1s, and 2 is at index 4.
  • Answer: option 1.
Q3sorted on a tuple

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
t = (3, 1, 2)
print(type(sorted(t)).__name__)
1
tuple
2
An error
3
list
4
None
Solution
Idea

sorted always returns a list.

Python
t = (3, 1, 2)
print(type(sorted(t)).__name__)
Output
list
  • The result type is list.
  • Answer: option 3.
Revision overview
ChangingNested list can change
Slots cannot
Whole tuple can be reassigned
Operations+ joins, * repeats
count(), index()
sorted(t) gives a list
Tuple useParts 10-11
AdvantagesMixed data
Slightly faster
Write-protected
KeysTuple of immutables: key
Tuple with a list: error
Revision: what can and cannot change, and why tuples are useful
Next · PracticeTry It Yourself
07
Practice

Try It Yourself

The seven tasks of the source, each with an executed solution.

Seven tasks from the source, to be done without looking back at the examples. Each has a really executed solution. Try the task first, then compare.

Task 1List basics

Create a list of 5 numbers, append two more, remove the smallest, then sort it.

Solution
Python
nums = [5, 2, 9, 1, 7]
nums.append(3)
nums.append(8)
nums.remove(min(nums))
nums.sort()
print(nums)
Output
[2, 3, 5, 7, 8, 9]

Start [5, 2, 9, 1, 7]; after the appends [5, 2, 9, 1, 7, 3, 8]; min is 1, which is removed; sorting gives the output.

Task 2Aliasing vs copying

Predict the output when b = a vs c = a.copy(), then b[0] and c[0] are both changed.

Solution
Python
a = [1, 2, 3]
b = a
c = a.copy()
b[0] = 99
c[0] = -1
print(a)
print(c)
Output
[99, 2, 3]
[-1, 2, 3]

b is an alias of a, so a shows 99. c is an independent copy, so its -1 stays in c.

Task 3Comparing lists

Predict the True/False result of comparing [1,2] < [2,1] and [] < [1], and explain why.

Solution
Python
print([1, 2] < [2, 1])
print([] < [1])
Output
True
True

The first compares element by element: 1 < 2 decides at once. The second: an empty list is a prefix of every list, so it is smaller.

Task 4Lists in functions

Write a function that appends to a list passed as a parameter, then show that the caller's list also changed.

Solution
Python
def grow(lst):
    lst.append(100)

data = [1, 2]
grow(data)
print(data)
Output
[1, 2, 100]

lst and data refer to the same list, so the append is visible outside.

Task 5Tuples

Create a tuple with a single element correctly, then try (and explain why it fails) to modify one of its items.

Solution
Python
t = (5,)
print(type(t))
Output
<class 'tuple'>
Python
t = (5,)
t[0] = 10
Error
TypeError: 'tuple' object does not support item assignment

The comma makes (5,) a tuple; tuples are immutable, so item assignment fails.

Task 6Tuple with a nested list

Create a tuple containing a list, then modify an item inside that nested list.

Solution
Python
t = (1, 2, [3, 4])
t[2][0] = 99
print(t)
Output
(1, 2, [99, 4])

Slot 2 still holds the same list; only that list's first item changed.

Task 7Concatenation and repetition

Combine two tuples with + and repeat one with *, and predict each output.

Solution
Python
print((1, 2) + (3, 4))
print((1, 2) * 2)
Output
(1, 2, 3, 4)
(1, 2, 1, 2)
Next · All partsWeek 6 Summary Sheet
08
All parts

Week 6 Summary Sheet

One page to revise all of Week 6: list vs tuple, the methods, the patterns and the common errors.

8.1List vs tuple

PropertyListTuple
Notation[]()
Creationlist()tuple()
MutabilityMutableImmutable
Elements storedAnyAny
OrderOrderedOrdered
DuplicatesAllowedAllowed
OperationsAdd, update, deleteNone (only build new tuples)
Indexing / slicingYesYes
SortingPossible (sort())Not in place (sorted() gives a list)
Dictionary keyNoYes, if all items are hashable

8.2Methods side by side

List methodsTuple methods
append(), extend(), insert()—
pop(), remove(), clear()—
sort(), reverse(), copy()—
count(), index()count(), index()

Patterns and how to use them

Copy, do not alias
Three copies
main.py
c1 = a.copy()
c2 = list(a)
c3 = a[:]

Use whenYou will change the new list and want the original untouched.

  1. b = a is only a second name.
  2. Copy with copy(), list() or [:].
  3. Nested lists: copy.deepcopy.
ExampleAn alias and a copy.
main.py
a = [1, 2]
b = a
c = a[:]
b.append(3)
print(a, c)
Output
[1, 2, 3] [1, 2]
append or extend
One item vs each item
main.py
l.append(x)
l.extend(seq)

Use whenAdding to a list in place.

  1. append adds its argument as one item.
  2. extend adds each item of a sequence.
  3. + does the same as extend but makes a new list.
ExampleThe lengths differ.
main.py
a = [1]
a.append([2, 3])
b = [1]
b.extend([2, 3])
print(len(a), len(b))
Output
2 3
sort or sorted
In place vs new
main.py
l.sort()
new = sorted(l)

Use whenYou need the items in order.

  1. l.sort() changes l and returns None.
  2. sorted(l) returns a new list, l unchanged.
  3. reverse=True for descending.
ExampleNever assign the result of sort().
main.py
l = [3, 1, 2]
print(sorted(l), l.sort(), l)
Output
[1, 2, 3] None [1, 2, 3]
A function that must not change its argument
Copy inside
main.py
def f(x):
    y = x.copy()
    y.append(1)
    return y

Use whenThe caller's list must stay as it was.

  1. Lists are passed as references.
  2. Changing the parameter changes the caller's list.
  3. Work on a copy and return it.
ExampleThe caller keeps [5].
main.py
def f(x):
    y = x.copy()
    y.append(1)
    return y

d = [5]
print(f(d), d)
Output
[5, 1] [5]
One-item tuple
The comma
main.py
t = ('a',)
n = ('a')

Use whenYou need a tuple with a single element.

  1. The comma makes the tuple.
  2. Without it you get the bare value.
  3. type() confirms.
ExampleTwo types.
main.py
print(type(('a',)).__name__, type(('a')).__name__)
Output
tuple str
Tuple as a dictionary key
Compound key
main.py
d[(name, subject)] = marks

Use whenA key made of several parts.

  1. Use a tuple of immutable items.
  2. A list, or a tuple holding a list, is not allowed.
  3. Read back with the same tuple.
ExampleTwo keys for one student.
main.py
d = {}
d[("Asha", "Maths")] = 91
d[("Asha", "CT")] = 88
print(d[("Asha", "CT")])
Output
88

8.3Common errors to avoid

MistakeWhat Python says
l + 4TypeError: can only concatenate list (not "int") to list
[].pop()IndexError: pop from empty list
l.remove(9), 9 not in lValueError: list.remove(x): x not in list
l.index(4), 4 not in lValueError: list.index(x): x not in list
[1, 2] < [1, "a"]TypeError: '<' not supported between instances of 'int' and 'str'
t[0] = 'A'TypeError: 'tuple' object does not support item assignment
t.append(3)AttributeError: 'tuple' object has no attribute 'append'
t.sort()AttributeError: 'tuple' object has no attribute 'sort'
tuple holding a list as a keyTypeError: cannot use 'tuple' as a dict key (unhashable type: 'list')
MistakeCorrect idea
l = l.sort()l becomes None; call l.sort() alone or use sorted(l).
l.insert(4, 0) read as "4 at index 0"The index comes first: 0 goes to index 4.
b = a to copyThat is an alias; use a.copy().
[[0] * 3] * 3 for a gridAll rows are the same list; build each row separately.
(5) for a tupleWrite (5,).

8.4Last-minute checklist

  • List notation, creation, and the + / * operators
  • Core list methods: append, extend, insert, pop, remove, sort, reverse
  • Aliasing vs copying a list: is, copy(), list(), slicing [:]
  • Comparing lists with ==, <, >
  • Lists passed to functions can be changed by the function
  • Tuple notation, the single-element comma trick, immutability
  • Why a nested mutable item inside a tuple can still change
  • Tuple concatenation (+) and repetition (*)
  • Advantages of tuples over lists
  • The full property comparison: list vs tuple
Revision overview
Lists[ ], mutable
+ joins, * repeats
11 methods
Aliasingb = a: same list
copy(), list(), [:]
Shallow copies
Compare and passFirst difference decides
Functions can change lists
Week 6Lists and tuples
Tuples( ), immutable
One item: ('a',)
t[0] = ...: TypeError
Tuple useNested list can change
count(), index()
Keys if hashable
Avoidl = l.sort()
insert order
Grid with *
Revision: all of Week 6 on one page
Back to top