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.
Chapters
- 01Lists: Notation, Properties, + and *Parts 1-2
- 02List MethodsPart 3
- 03Aliasing and CopyingParts 4-5
- 04Comparing Lists and Passing Them to FunctionsParts 6-7
- 05Tuples: Notation, Indexing and ImmutabilityParts 8-9
- 06Changing Tuples, Methods and AdvantagesParts 10-11
- 07Try It YourselfPractice zone
- 08Week 6 Summary SheetAll parts
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
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.
| Property | Value |
|---|---|
| Notation | [ ] |
| Creation | list() or l = [] |
| Mutability | Mutable: we can change the order of items or reassign an item |
| Types of elements stored | Any |
| Order of elements | Ordered |
| Duplicate elements | Allowed |
| Sorting | Possible |
l1 = []
l2 = list()
l3 = [10, "ten", 10.0, True, 10]
print(l1, l2)
print(l3)
print(len(l3))[] []
[10, 'ten', 10.0, True, 10]
5One 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):
print(list("abc"))
print(list(range(4)))
print(list((1, 2, 3)))['a', 'b', 'c']
[0, 1, 2, 3]
[1, 2, 3]1.2Indexing, slicing and changing an item
l = [10, 20, 30, 40, 50]
print(l[0], l[-1])
print(l[1:3])
l[0] = 99
print(l)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.
l1 = [1, 2, 3]
l2 = [4, 5]
l3 = l1 + l2
l4 = l1 * 3
print(l3)
print(l4)[1, 2, 3, 4, 5]
[1, 2, 3, 1, 2, 3, 1, 2, 3]Both build a new list; l1 and l2 are unchanged. Two details worth knowing (extra):
l = [1, 2, 3]
l = l + 4TypeError: 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:
print([1, 2] * 0)
print([0] * 5)[]
[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:
grid = [[0] * 3] * 3
grid[0][0] = 1
print(grid)[[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:
grid = [[0] * 3 for i in range(3)]
grid[0][0] = 1
print(grid)[[1, 0, 0], [0, 0, 0], [0, 0, 0]]1.5Exam tips and common mistakes
- For
+and*, work out the new list first, then answer length or index questions. - Count nested lists as one item each.
- Writing
l + 4instead ofl + [4]. - Building a grid with
[[0] * n] * n. - Thinking
+changes the original list.
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
l = [2, 4] * 2 + [6]
print(len(l), l[-2])Do * before +.
l = [2, 4] * 2 + [6]
print(len(l), l[-2])5 4[2, 4] * 2is[2, 4, 2, 4]; adding[6]gives 5 items.l[-2]is the 4 before the 6.- Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
l = [1, 2, 3]
l[1] = [7, 8]
print(l, len(l))[1, 7, 8, 3] 4[1, 7, 3] 3[1, [7, 8], 3] 3An item can be any value, including a list.
l = [1, 2, 3]
l[1] = [7, 8]
print(l, len(l))[1, [7, 8], 3] 3l[1]becomes the list[7, 8]; the length stays 3.- Answer: option 3.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
rows = [[0] * 2] * 2
rows[1][1] = 5
print(rows)[[0, 5], [0, 5]][[0, 0], [0, 5]][[0, 5], [0, 0]]* repeats the same inner list.
rows = [[0] * 2] * 2
rows[1][1] = 5
print(rows)[[0, 5], [0, 5]]- Both rows are the same list, so the change shows in both.
- Answer: option 1.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
l = list("CT")
print(l + ["!"])['CT', '!']['CT!']CT!['C', 'T', '!']list() splits a string into characters.
l = list("CT")
print(l + ["!"])['C', 'T', '!']list("CT")is['C', 'T'].- Answer: option 4.
Ordered, mutable
Any types, duplicates
l[1:3]
l[0] = 99 works
* repeats
Both make new lists
Same inner list
Build rows separately
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
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[1, 2, 3, 4]
[1, 2, 3, 4, 4, 5]
[4, 6, 8, 9]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.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)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: []| Method | What it does | Returns | Changes the list? |
|---|---|---|---|
append(x) | adds x at the end | None | yes |
extend(seq) | adds every item of seq | None | yes |
insert(i, x) | puts x at index i | None | yes |
pop() / pop(i) | removes the last item / the item at i | the removed item | yes |
remove(x) | removes the first x | None | yes |
count(x) | counts x | an int | no |
index(x) | finds the first x | its index | no |
sort() | sorts in place | None | yes |
reverse() | reverses in place | None | yes |
copy() | makes a shallow copy | a new list | no |
clear() | removes everything | None | yes |
2.2append and extend
a = [1, 2]
a.append([3, 4])
print(a, len(a))
b = [1, 2]
b.extend([3, 4])
print(b, len(b))[1, 2, [3, 4]] 3
[1, 2, 3, 4] 4append 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)
l = [10, 20, 30]
l.insert(0, 5)
print(l)
l.insert(2, 15)
print(l)
l.insert(100, 99)
print(l)[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
l = [10, 20, 30, 40]
last = l.pop()
print(last, l)
first = l.pop(0)
print(first, l)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:
l = [3, 1, 3, 2]
l.remove(3)
print(l)[1, 3, 2]Both complain when there is nothing to remove (extra):
l = []
l.pop()IndexError: pop from empty listl = [3, 1, 2]
l.remove(9)ValueError: list.remove(x): x not in list2.5count and index
l = [5, 7, 5, 9, 5]
print(l.count(5))
print(l.index(5))
print(l.index(9))3
0
3index gives the position of the first match. A value that is not there raises an error rather than returning -1 (extra):
l = [5, 7, 9]
print(l.index(4))ValueError: list.index(x): x not in list2.6sort, sorted and reverse
l = [3, 1, 2]
l.sort()
print(l)
l.sort(reverse=True)
print(l)
words = ["pear", "Apple", "fig"]
words.sort()
print(words)[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.
l = [3, 1, 2]
l = l.sort()
print(l)NoneTo keep the original and get a sorted copy, use the built-in sorted() (extra):
l = [3, 1, 2]
s = sorted(l)
print(s, l)[1, 2, 3] [3, 1, 2]l = [1, 2, 3]
print(l[::-1], l)
l.reverse()
print(l)[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
- Ask for each method: does it change the list, and what does it return?
- Trace the list after every line.
- Reading
insert(i, x)as value first. - Writing
l = l.sort(), which leavesNone. - Expecting
removeto delete every copy of a value. - Using
appendto join two lists.
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
What does the program print?
l = [1, 2, 3]
l.append([4, 5])
l.extend([6, 7])
print(len(l))append adds one item, extend adds each.
l = [1, 2, 3]
l.append([4, 5])
l.extend([6, 7])
print(len(l))6- 3 items, +1 (the list [4, 5]), +2 (6 and 7).
- Answer: 6
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
l = [10, 20, 30, 40]
x = l.pop(1)
l.insert(0, x)
print(l)[10, 20, 30, 40][20, 30, 40][20, 10, 30, 40][10, 30, 40, 20]pop(1) removes and returns 20.
l = [10, 20, 30, 40]
x = l.pop(1)
l.insert(0, x)
print(l)[20, 10, 30, 40]- After pop:
[10, 30, 40]; insert 20 at index 0. - Answer: option 3.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
l = [4, 1, 4, 2, 4]
l.remove(4)
print(l.count(4), l.index(4))remove deletes only the first 4.
l = [4, 1, 4, 2, 4]
l.remove(4)
print(l.count(4), l.index(4))2 1- The list becomes
[1, 4, 2, 4]: two 4s, the first at index 1. - Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
l = [3, 1, 2]
r = l.sort()
print(r, l)[1, 2, 3] [1, 2, 3][1, 2, 3] [3, 1, 2]None [3, 1, 2]None [1, 2, 3]sort works in place.
l = [3, 1, 2]
r = l.sort()
print(r, l)None [1, 2, 3]risNone;lis sorted.- Answer: option 4.
Numerical Answer Type (NAT).
What does the program print?
l = [5, 3, 8]
s = sorted(l, reverse=True)
print(s[0] - l[0])sorted returns a new list.
l = [5, 3, 8]
s = sorted(l, reverse=True)
print(s[0] - l[0])3s = [8, 5, 3]whilelstays[5, 3, 8]: 8 − 5.- Answer: 3
extend(seq): each item
insert(i, x): index first
remove(x): first match
clear(): everything
index(x): first match
Missing: ValueError
sorted(): new list
reverse() vs [::-1]
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.
a = [1, 2, 3]
b = a
print(b is a)
c = a.copy()
print(c is a)True
FalseSince a list is mutable, a change made through one alias affects the other:
a = [1, 2, 3, 4]
b = a
b[0] = 17
print(a)[17, 2, 3, 4]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
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)[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:
a = [[1, 2], [3, 4]]
b = a.copy()
b[0][0] = 99
print(a)
print(b is a, b[0] is a[0])[[99, 2], [3, 4]]
False TrueFor a fully independent copy of nested lists, use copy.deepcopy:
import copy
a = [[1, 2], [3, 4]]
b = copy.deepcopy(a)
b[0][0] = 99
print(a)
print(b)[[1, 2], [3, 4]]
[[99, 2], [3, 4]]3.4== against is
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b, a is b)True False== asks "same contents?"; is asks "the same object?". Two lists built separately can be equal without being the same object.
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
- Draw names and arrows: which names point to which list?
- After a copy, ask whether the items are themselves lists.
- Thinking
b = acopies the list. - Assuming
copy()also copies inner lists. - Using
isto compare contents.
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
a = [1, 2, 3]
b = a
b.append(4)
c = a[:]
c.append(5)
print(len(a), len(c))b is an alias, c is a copy.
a = [1, 2, 3]
b = a
b.append(4)
c = a[:]
c.append(5)
print(len(a), len(c))4 5b.append(4)changes a (length 4). c was copied after that, then got 5 (length 5).- Answer: option 1.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
a = [[1], [2]]
b = list(a)
b[0].append(9)
b[1] = [7]
print(a)[[1], [2]][[1, 9], [7]][[1, 9], [2]][[1], [7]]list(a) copies the outer list only.
a = [[1], [2]]
b = list(a)
b[0].append(9)
b[1] = [7]
print(a)[[1, 9], [2]]b[0]is the same inner list asa[0], so 9 shows in a.- Replacing
b[1]changes only b. - Answer: option 3.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
a = [1, 2]
b = [1, 2]
c = a
print(a == b, a is b, a is c)Contents against identity.
a = [1, 2]
b = [1, 2]
c = a
print(a == b, a is b, a is c)True False True- a and b are equal but different objects; c is a.
- Answer: option 2.
Same object
Change shows in both
Shallow: inner lists shared
deepcopy for nested
is same object
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.
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])True
False
True
True
True
True
True- Compare the first elements. If they differ, that decides the answer.
- If they are equal, move to the next pair, and so on.
- 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)
print(["apple"] < ["banana"])
print([2, "a"] < [3])True
TrueStrings 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:
print([1, 2] < [1, "a"])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).
def add(x):
x.append(1)
return x
x = [5]
print(add(x))
print(x)[5, 1]
[5, 1]- 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:
def reset(lst):
lst = [0]
return lst
data = [5, 6]
print(reset(data))
print(data)[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:
def bump(n):
n = n + 1
return n
k = 5
print(bump(k))
print(k)6
5To leave the caller's list untouched, copy inside the function and return the copy:
def add_safe(x):
y = x.copy()
y.append(1)
return y
x = [5]
print(add_safe(x))
print(x)[5, 1]
[5]add has a side effect on its argument; add_safe has none.4.4Exam tips and common mistakes
- For comparisons, find the first position where the lists differ.
- Inside a function, check whether the parameter is changed or rebound.
- 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)
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
print([2, 1, 9] < [2, 3])Compare position by position.
print([2, 1, 9] < [2, 3])True- 2 equals 2; then 1 < 3 decides. The 9 is never compared.
- Answer: option 1.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
print([1, 2, 3] > [1, 2])A prefix is smaller.
print([1, 2, 3] > [1, 2])True[1, 2]is a prefix of[1, 2, 3], so the longer list is greater.- Answer: option 1.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
def f(lst):
lst.append(0)
lst = [9]
lst.append(1)
data = [5]
f(data)
print(data)[5][5, 0][9, 1][5, 0, 1]Only changes before the rebinding reach the caller.
def f(lst):
lst.append(0)
lst = [9]
lst.append(1)
data = [5]
f(data)
print(data)[5, 0]append(0)changes data; afterlst = [9]the function works on a new list.- Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
def g(n, lst):
n = n * 2
lst[0] = lst[0] * 2
a = 3
b = [3]
g(a, b)
print(a, b)An int is rebound; the list is changed in place.
def g(n, lst):
n = n * 2
lst[0] = lst[0] * 2
a = 3
b = [3]
g(a, b)
print(a, b)3 [6]- a stays 3;
b[0]is doubled to 6. - Answer: option 3.
< > element by element
First difference decides
[] < [1]
int vs str: TypeError
Change in place: caller sees it
Rebind: caller does not
Return the copy
Tuples: Notation, Indexing and Immutability
Round brackets, the single-item comma, indexing and slicing, and why t[0] = ... fails.
5.1Notation and properties
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.
| Property | Value |
|---|---|
| Notation | ( ) |
| Creation | tuple() or t = (10,) |
| Mutability | Immutable |
| Types of elements stored | Any |
| Order of elements | Ordered |
| Duplicate elements | Allowed |
| Operations | Indexing, slicing, iteration |
| Sorting | Not possible in place |
| Methods | count(), 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:
t = 1, 2, 3, 4
print(t, type(t))
t = (1, 2, 3, 4)
print(t)
e = ()
print(e, len(e))(1, 2, 3, 4) <class 'tuple'>
(1, 2, 3, 4)
() 05.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.
t1 = ('a',)
t2 = ('a')
print(type(t1), type(t2))<class 'tuple'> <class 'str'>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:
t = tuple('hello')
print(t)
print(tuple([1, 2]))('h', 'e', 'l', 'l', 'o')
(1, 2)5.3Indexing, slicing and immutability
t = ('a', 'b', 'c')
print(t[0])
t = (1, 2, 3, 4)
print(t[1:3])
print(t[-1])a
(2, 3)
4Indexing 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:
t = ('a', 'b', 'c')
t[0] = 'A'TypeError: 'tuple' object does not support item assignmentTuples have no adding or removing methods either (extra):
t = (1, 2)
t.append(3)AttributeError: 'tuple' object has no attribute 'append'5.4Exam tips and common mistakes
- Look for the comma to decide whether something is a tuple.
- Any attempt to change a slot of a tuple is a TypeError.
- Writing
(5)for a one-item tuple. - Expecting
appendorsorton a tuple.
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
t = (7)
u = (7,)
print(type(t) == type(u))Which one is a tuple?
t = (7)
u = (7,)
print(type(t) == type(u))Falsetis the int 7,uis a tuple.- Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
t = tuple("abc") + ("d",)
print(len(t), t[1:3])tuple("abc") has three items.
t = tuple("abc") + ("d",)
print(len(t), t[1:3])4 ('b', 'c')- The tuple is
('a', 'b', 'c', 'd'); its slice 1:3 is('b', 'c'). - Answer: option 3.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
t = (1, 2, 3)
print(t[::-1])[3, 2, 1](1, 2, 3)(3, 2, 1)A slice of a tuple is a tuple.
t = (1, 2, 3)
print(t[::-1])(3, 2, 1)[::-1]reverses it.- Answer: option 4.
Ordered, immutable
Any types, duplicates
('a') is a str
t[1:3] is a tuple
No append, no sort
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.
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)(4, 2, 3, [9, 5])
('g', 'a', 'g', 'n', 'e', 'e', 't')my_tuple = (4, 2, 3, [6, 5])
my_tuple[1] = 9TypeError: 'tuple' object does not support item assignmentThe 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.
print((1, 2, 3) + (4, 5, 6))
print((1, 2) * 3)(1, 2, 3, 4, 5, 6)
(1, 2, 1, 2, 1, 2)6.3Tuple methods
t1 = ('a', 'p', 'p', 'l', 'e')
print(t1.count('p'))
print(t1.index('l'))2
3Only two methods: count() and index(), both read-only. The built-in sorted() still works on a tuple, but returns a list (extra):
t = (3, 1, 2)
print(sorted(t))
print(tuple(sorted(t)))[1, 2, 3]
(1, 2, 3)t = (3, 1, 2)
t.sort()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.
marks = {}
marks[("Asha", "Maths")] = 91
marks[("Asha", "Physics")] = 84
print(marks[("Asha", "Maths")])91d = {}
d[(1, [2, 3])] = "x"TypeError: cannot use 'tuple' as a dict key (unhashable type: 'list')d = {}
d[[1, 2]] = "x"TypeError: cannot use 'list' as a dict key (unhashable type: 'list')6.5Packing and unpacking (extra)
a, b = 1, 2
a, b = b, a
print(a, b)2 11, 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
- 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.
- 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)
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
t = (1, [2, 3], 4)
t[1].append(5)
print(len(t), len(t[1]))The list inside can grow; the tuple cannot.
t = (1, [2, 3], 4)
t[1].append(5)
print(len(t), len(t[1]))3 3- The tuple still has 3 slots; the inner list now has 3 items.
- Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
t = (0, 1) * 2 + (2,)
print(t.count(1), t.index(2))Build the tuple first.
t = (0, 1) * 2 + (2,)
print(t.count(1), t.index(2))2 4(0, 1, 0, 1, 2): two 1s, and 2 is at index 4.- Answer: option 1.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
t = (3, 1, 2)
print(type(sorted(t)).__name__)sorted always returns a list.
t = (3, 1, 2)
print(type(sorted(t)).__name__)list- The result type is list.
- Answer: option 3.
Slots cannot
Whole tuple can be reassigned
count(), index()
sorted(t) gives a list
Slightly faster
Write-protected
Tuple with a list: error
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.
Create a list of 5 numbers, append two more, remove the smallest, then sort it.
nums = [5, 2, 9, 1, 7]
nums.append(3)
nums.append(8)
nums.remove(min(nums))
nums.sort()
print(nums)[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.
Predict the output when b = a vs c = a.copy(), then b[0] and c[0] are both changed.
a = [1, 2, 3]
b = a
c = a.copy()
b[0] = 99
c[0] = -1
print(a)
print(c)[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.
Predict the True/False result of comparing [1,2] < [2,1] and [] < [1], and explain why.
print([1, 2] < [2, 1])
print([] < [1])True
TrueThe 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.
Write a function that appends to a list passed as a parameter, then show that the caller's list also changed.
def grow(lst):
lst.append(100)
data = [1, 2]
grow(data)
print(data)[1, 2, 100]lst and data refer to the same list, so the append is visible outside.
Create a tuple with a single element correctly, then try (and explain why it fails) to modify one of its items.
t = (5,)
print(type(t))<class 'tuple'>t = (5,)
t[0] = 10TypeError: 'tuple' object does not support item assignmentThe comma makes (5,) a tuple; tuples are immutable, so item assignment fails.
Create a tuple containing a list, then modify an item inside that nested list.
t = (1, 2, [3, 4])
t[2][0] = 99
print(t)(1, 2, [99, 4])Slot 2 still holds the same list; only that list's first item changed.
Combine two tuples with + and repeat one with *, and predict each output.
print((1, 2) + (3, 4))
print((1, 2) * 2)(1, 2, 3, 4)
(1, 2, 1, 2)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
| Property | List | Tuple |
|---|---|---|
| Notation | [] | () |
| Creation | list() | tuple() |
| Mutability | Mutable | Immutable |
| Elements stored | Any | Any |
| Order | Ordered | Ordered |
| Duplicates | Allowed | Allowed |
| Operations | Add, update, delete | None (only build new tuples) |
| Indexing / slicing | Yes | Yes |
| Sorting | Possible (sort()) | Not in place (sorted() gives a list) |
| Dictionary key | No | Yes, if all items are hashable |
8.2Methods side by side
| List methods | Tuple methods |
|---|---|
append(), extend(), insert() | — |
pop(), remove(), clear() | — |
sort(), reverse(), copy() | — |
count(), index() | count(), index() |
Patterns and how to use them
c1 = a.copy()
c2 = list(a)
c3 = a[:]Use whenYou will change the new list and want the original untouched.
b = ais only a second name.- Copy with
copy(),list()or[:]. - Nested lists:
copy.deepcopy.
a = [1, 2]
b = a
c = a[:]
b.append(3)
print(a, c)[1, 2, 3] [1, 2]l.append(x)
l.extend(seq)Use whenAdding to a list in place.
appendadds its argument as one item.extendadds each item of a sequence.+does the same as extend but makes a new list.
a = [1]
a.append([2, 3])
b = [1]
b.extend([2, 3])
print(len(a), len(b))2 3l.sort()
new = sorted(l)Use whenYou need the items in order.
l.sort()changes l and returnsNone.sorted(l)returns a new list, l unchanged.reverse=Truefor descending.
l = [3, 1, 2]
print(sorted(l), l.sort(), l)[1, 2, 3] None [1, 2, 3]def f(x):
y = x.copy()
y.append(1)
return yUse whenThe caller's list must stay as it was.
- Lists are passed as references.
- Changing the parameter changes the caller's list.
- Work on a copy and return it.
def f(x):
y = x.copy()
y.append(1)
return y
d = [5]
print(f(d), d)[5, 1] [5]t = ('a',)
n = ('a')Use whenYou need a tuple with a single element.
- The comma makes the tuple.
- Without it you get the bare value.
type()confirms.
print(type(('a',)).__name__, type(('a')).__name__)tuple strd[(name, subject)] = marksUse whenA key made of several parts.
- Use a tuple of immutable items.
- A list, or a tuple holding a list, is not allowed.
- Read back with the same tuple.
d = {}
d[("Asha", "Maths")] = 91
d[("Asha", "CT")] = 88
print(d[("Asha", "CT")])888.3Common errors to avoid
| Mistake | What Python says |
|---|---|
l + 4 | TypeError: can only concatenate list (not "int") to list |
[].pop() | IndexError: pop from empty list |
l.remove(9), 9 not in l | ValueError: list.remove(x): x not in list |
l.index(4), 4 not in l | ValueError: 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 key | TypeError: cannot use 'tuple' as a dict key (unhashable type: 'list') |
| Mistake | Correct 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 copy | That is an alias; use a.copy(). |
[[0] * 3] * 3 for a grid | All rows are the same list; build each row separately. |
(5) for a tuple | Write (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
+ joins, * repeats
11 methods
copy(), list(), [:]
Shallow copies
Functions can change lists
One item: ('a',)
t[0] = ...: TypeError
count(), index()
Keys if hashable
insert order
Grid with *