Python Tuples
What you will learn
- What a tuple is and how to create one
- The one-item trap: why
(5)is not a tuple - Indexing, slicing and looping, as with lists
- That tuples are immutable, and what that allows
countandindex, joining and comparing- When to choose a tuple instead of a list
1. What is a tuple?
A tuple (type tuple) is an ordered collection of items that cannot be changed after it is made. It looks like a list, but is written with round brackets:
t = (10, 20, 30)
print(t, type(t), len(t))
print(t[0], t[-1], t[1:])
(10, 20, 30) <class 'tuple'> 3
10 30 (20, 30)
Everything you learned about reading a list works on a tuple: indexing (positive and negative), slicing, len, in, loops, min, max, sum and sorted. What a tuple lacks is the ability to change (section 3).
A tuple can hold items of any type, even lists and other tuples:
mixed = (1, "two", [3, 4], (5, 6))
print(mixed[2], mixed[3][0], len(mixed))
[3, 4] 5 4
Quick check: what is `(1, 2, 3)[1:]`?
(2, 3). A slice of a tuple is a tuple.
2. Creating tuples
e = ()
no_paren = 1, 2, 3
print(e, no_paren)
print(tuple(), tuple([1, 2]), tuple("ab"), tuple(range(3)))
() (1, 2, 3)
() (1, 2) ('a', 'b') (0, 1, 2)
()is the empty tuple, and so istuple().- The comma makes a tuple, not the brackets:
1, 2, 3is a tuple. Brackets only help to read it, and are needed when the tuple sits inside something else. tuple(collection)turns any collection into a tuple.
The one-item trap
Brackets alone do not make a tuple. They are the brackets of ordinary maths:
print(type((5)), type((5,)))
print((5) * 3, (5,) * 3)
<class 'int'> <class 'tuple'>
15 (5, 5, 5)
(5) is just the number 5. A tuple of one item needs a trailing comma: (5,). This is also how Python writes it back.
3. Tuples are immutable
A tuple cannot be changed: you cannot assign to an item, add, remove or sort it in place:
t = (10, 20, 30)
t[0] = 99
TypeError: 'tuple' object does not support item assignment
t.append(1)
AttributeError: 'tuple' object has no attribute 'append'
And del t[0] raises TypeError: 'tuple' object doesn't support item deletion.
You can still build a new tuple from an old one, with +, slices and *:
print(t + (40,))
print(t * 2)
print(t[:2] + (99,) + t[2:])
(10, 20, 30, 40)
(10, 20, 30, 10, 20, 30)
(10, 20, 99, 30)
Even += builds a new tuple and moves the name (lesson 2.6), so any other name keeps the old one:
a = (1, 2)
b = a
a += (3,)
print(a, b, a is b)
(1, 2, 3) (1, 2) False
+ joins tuples only with tuples: (1, 2) + [3] is a TypeError.
A tuple can hold a list that changes
The tuple is fixed, but a mutable item inside it can still change (lessons 2.6 and 7.5):
mixed = (1, "two", [3, 4], (5, 6))
mixed[2].append(99)
print(mixed)
(1, 'two', [3, 4, 99], (5, 6))
The tuple still holds the same list; the list itself grew.
4. Methods: count and index
Because tuples cannot change, they have only two methods, and you know both from lists:
t = (10, 20, 30, 20)
print(t.count(20), t.index(30))
print(20 in t, 25 not in t)
2 2
True True
count(x) counts matches and index(x) gives the first position (an error if missing).
5. Comparing, sorting and looping
Tuples compare item by item from the left, like lists and text (lesson 5.1), and a tuple is never equal to a list:
print((1, 2) < (1, 3), (1, 2, 3) > (1, 2), (1, 2) == [1, 2])
print(sorted((3, 1, 2)), type(sorted((3, 1, 2))))
print(tuple(sorted((3, 1, 2))))
True True False
[1, 2, 3] <class 'list'>
(1, 2, 3)
sorted always returns a list. Wrap it in tuple(...) if you want a tuple back. Looping is the same as for lists:
for pair in [(1, "a"), (2, "b")]:
print(pair, pair[0], pair[1], end="; ")
print()
(1, 'a') 1 a; (2, 'b') 2 b;
An empty tuple is false, and any other tuple is true, even (0,) or (None,) (lesson 5.3).
6. Why use a tuple?
A list can do everything a tuple can, and more. So why have tuples?
| Reason | Meaning |
|---|---|
| A fixed record | (x, y) or (year, month, day): a group of values that belong together and should not change |
| Safety | nobody can change it by accident, even if it is passed around |
| Dictionary keys and set items | a tuple of immutable items is hashable, so it can be a key (see below) |
| Returning several values | functions return tuples (lesson 8.2) |
| Slightly smaller | in a test, (1, 2, 3) used 64 bytes and [1, 2, 3] used 88 on one computer |
Hashable: tuples as dictionary keys
A dictionary key must never change (chapter 9). A tuple whose items are themselves unchangeable qualifies. A list does not:
d = {(0, 0): "origin", (1, 2): "point"}
print(d[(0, 0)], d[1, 2], (3, 4) in d)
origin point False
{[1, 2]: "x"}
TypeError: unhashable type: 'list'
A tuple that contains a list is also unhashable, because its contents could change: hash((1, [2])) raises the same TypeError.
List or tuple?
list |
tuple |
|
|---|---|---|
| written | [1, 2] |
(1, 2) |
| can change | yes | no |
| methods | many | count, index |
| typical use | a collection that grows, shrinks or is sorted | a fixed group of related values |
| dictionary key | no | yes, if all items are immutable |
A common rule of thumb: use a list for many similar items (a list of marks), and a tuple for a few different things that make one record (name, age, city).
Worked example: points on a map
Store points as tuples, find the distance between two, and pick the point furthest right.
import math
a = (0, 0)
b = (3, 4)
points = [(2, 3), (1, 5), (2, 1)]
print(math.dist(a, b))
print(max(points))
print(sorted(points))
print(min(points, key=lambda p: p[1]))
5.0
(2, 3)
[(1, 5), (2, 1), (2, 3)]
(2, 1)
| Call | Result | Why |
|---|---|---|
math.dist(a, b) |
5.0 |
the straight-line distance (lesson 3.6) |
max(points) |
(2, 3) |
tuples compare left to right: the largest first value, then the largest second value |
sorted(points) |
by x, then y | the same rule |
min(points, key=...) |
(2, 1) |
the point with the smallest y |
The points are made up for the example.
Common mistakes
- Writing
(5)for a one-item tuple. Write(5,). - Trying to change a tuple (
t[0] = 1,t.append(...)). Build a new tuple, or use a list. - Joining a tuple with a list using
+. - Thinking a tuple holding a list is frozen all the way down.
- Expecting
sortedto return a tuple. It returns a list. - Using a tuple that contains a list as a dictionary key.
Key takeaways
- A tuple is an ordered, unchangeable collection written with commas, usually in round brackets.
- A one-item tuple needs a trailing comma:
(5,). - Indexing, slicing,
len,in, loops and comparisons work as for lists; the only methods arecountandindex. - You change a tuple by building a new one; a list inside a tuple can still change.
- Use tuples for fixed records, dictionary keys and returned values; use lists for collections that change.
Practice
1. Which of these is a tuple: (7), (7,), [7], 7,?
Show answer
(7,) and 7, are tuples. (7) is the number 7 and [7] is a list.
2. What does (1, 2, 3, 4)[1:3] give?
Show answer
(2, 3).
3. What error does t = (1, 2) followed by t[0] = 9 cause?
Show answer
TypeError: 'tuple' object does not support item assignment.
4. Make a new tuple from (1, 2, 3) with 99 put at the end.
Show answer
(1, 2, 3) + (99,), which gives (1, 2, 3, 99).
5. Why can (1, 2) be a dictionary key but [1, 2] cannot?
Show answer
A tuple of unchangeable items is hashable and never changes. A list can change, so it is unhashable and Python refuses it as a key.
6. Which would you use for a person's (name, age, city), and which for the marks of a whole class?
Show answer
A tuple for the fixed record (name, age, city), and a list for the class marks, which may grow.