Sub topic 1
What a Tuple Is and When to Use One
Prerequisites
This chapter assumes you can:
- Write basic Python syntax and assign variables.
- Index into a list, such as
items[0]. - Define and call a function.
- Write a
forloop.
Later chapters cover how to build tuples, immutability in detail, and unpacking. Here you get the working model and a way to decide when a tuple is the right choice.
The working model
A tuple is an ordered sequence of values that cannot be resized or have its items rebound after creation. "Ordered" means each item has a fixed position, starting at index 0. "Immutable" means the tuple's length and the object each position refers to never change.
record = ("Oslo", 59.91, 10.75)
print(record[0])
print(len(record))
print(type(record))
readings = [20.5, 21.0, 19.8]
readings.append(22.1)
print(readings)
try:
record.append(1)
except AttributeError as e:
print(e)The tuple supports reading (record[0], len) but has no append, so the last call fails with 'tuple' object has no attribute 'append'. The list accepts the new item.
Tuple or list
Both are ordered sequences that you index and loop over. The difference is in what each one signals to a reader and what each one allows.
| Feature | Tuple | List |
|---|---|---|
| Can grow or shrink | No | Yes |
| Can replace an item | No | Yes |
| Typical contents | A few values with different roles | Many values of the same kind |
| Can be a dictionary key | Yes, if all items are hashable | No |
| Typical length | Fixed by design | Varies at runtime |
A useful rule of thumb: a list is a collection of similar things whose count changes, such as a list of scores. A tuple is a record where each position has its own meaning, such as (name, latitude, longitude).
When to use a tuple
Choose a tuple in these situations:
- A small fixed record. The position of each value carries meaning, as in a coordinate pair or an RGB colour.
- Returning several values from a function. Python returns them as one tuple, which the caller can take apart. You will use this often.
- A composite dictionary key. A pair like
(row, column)can identify a grid cell. - Data that should not change by accident. Passing a tuple tells the reader, and enforces, that the function cannot add or remove items.
Choose a list when you need to append, remove, sort in place, or build the sequence up item by item.
A worked example
A function that reports a range of values is a natural fit for a tuple, because it always returns exactly two things with different roles.
def bounds(values):
return min(values), max(values)
result = bounds([3, 1, 4, 1, 5])
print(result)
print(result[0], result[1])The output is (1, 5) and then 1 5. The function always returns two values, in the same order, so a tuple is correct. A list would work, but it would suggest the length might vary.
Common mistakes at this stage
- Using a tuple for data you later need to extend, then rebuilding it by hand. Use a list instead.
- Reading items by magic index, such as
record[2], when the record has many fields. Past three or four fields, a named tuple or a class is easier to read. A later chapter covers named tuples. - Assuming a tuple is always faster or smaller than a list in a way that matters. Tuples are slightly leaner, but choose by meaning first, not by speed.
Exercise
You are storing the name, birth year and country of a single person, and you will never add fields at runtime. Would you choose a tuple or a list, and why?
Show answer
A tuple. The data is a small fixed record where each position has its own meaning (name, year, country), and the length never changes. A list suggests a variable number of similar items, which does not match this data.
Exercise
A script reads lines from a file and collects each line into a sequence as it goes. Should the sequence be a tuple or a list?
Show answer
A list. The script adds items one at a time, and a tuple cannot grow after it is created.