Sub topic 1
What a tuple is and when to use one
Prerequisites
This chapter assumes you can already do the following:
- Write basic Python: variables, expressions,
print, andifstatements. - Create lists and read items by index, such as
items[0]. - Define and call a function.
- Write a
forloop.
You don't need to know about unpacking yet. The later chapters cover it. This chapter explains what a tuple is and how to decide when it is the right container.
What a tuple is
A tuple is an ordered, fixed-size sequence of values. Once you create it, you cannot add, remove or replace its items. You write one with commas, usually inside parentheses.
point = (3, 4)
print(type(point))
print(point[0], point[1])
print(len(point))
print(point == (3, 4))This prints <class 'tuple'>, then 3 4, then 2, then True.
A tuple has the same read operations as a list: indexing, slicing, len, in, iteration and comparison. It has none of the operations that change a list, such as append, remove, sort or item assignment. Only two methods exist on a tuple:
t = (1, 2, 2, 3)
print(t.count(2))
print(t.index(3))This prints 2 and 3. count returns how many times a value appears. index returns the position of the first match.
Tuples are not limited to two items, and they can hold any mix of types. A tuple can be empty, written (). Details of construction, including the one-element case, come in the next chapter.
What "immutable" means here
Python calls a tuple immutable. This means the tuple itself cannot change after creation. Trying to change it raises an error:
point = (3, 4)
try:
point[0] = 10
except TypeError as e:
print(e)This prints 'tuple' object does not support item assignment.
To get a modified version, you build a new tuple and, if you want, rebind the name to it:
point = (3, 4)
bigger = point + (5,)
print(point)
print(bigger)The output is (3, 4) and then (3, 4, 5). The original tuple is untouched. The + operator made a second tuple.
Immutability applies to which objects the tuple holds. It does not apply to the contents of those objects. If a tuple holds a list, you can still change that list. A later chapter covers this limit in detail. For now, remember this: the tuple's slots are fixed, but a mutable object in a slot can still change.
Tuple versus list
Both are ordered sequences. The differences are small in syntax and large in meaning.
| Property | Tuple | List |
|---|---|---|
| Can change size or items | No | Yes |
| Literal syntax | `(1, 2, 3)` | `[1, 2, 3]` |
| Can be a dictionary key (if all items are hashable) | Yes | No |
| Methods | `count`, `index` | Many, such as `append`, `sort`, `pop` |
| Typical use | A fixed group of related values | A collection that grows, shrinks or is reordered |
A list says "this is a collection of things, and the number may change." A tuple says "this is one composite value with a fixed shape." Readers of your code take that signal from the type you choose.
A common convention: shape versus sequence
Experienced Python programmers often follow this convention:
- Use a list for many items of the same kind, where the count is not known in advance. Examples are lines of a file, user names, and measurements.
- Use a tuple for a few items of different kinds, where each position has its own meaning. Examples are
(name, age, city)and(latitude, longitude).
This is a convention, not a rule the language enforces. It explains why a function that returns (status, message) returns a tuple, and why a function that returns every matching file returns a list.
record = ("Ada", 36, "London")
print(record[0])
print(record[2])Position 0 is always a name and position 2 is always a city. Changing the order or the length would change what the record means, which is why the fixed shape of a tuple fits.
Why immutability is useful
Immutability gives you three practical benefits.
- Safety against accidental changes. If you pass a tuple to a function, that function cannot add or remove items from it. You don't need to defend with a copy.
- Hashability. An object is hashable if Python can compute a stable number for it from its contents. Dictionary keys and set members must be hashable. A tuple whose items are all hashable is itself hashable.
- A small speed and memory edge. Tuples are slightly smaller than lists with the same items, because a list reserves extra room for growth.
Here is the hashability benefit in practice:
visited = {(0, 0), (0, 1)}
print((0, 1) in visited)
try:
bad = {[0, 0]}
except TypeError as e:
print(e)The first line prints True. The second prints unhashable type: 'list'. A list can change, so Python cannot give it a hash that stays valid. The chapter on tuples as keys covers this fully.
The size difference is easy to check, though the exact numbers depend on your Python version and platform:
import sys
print(sys.getsizeof((1, 2, 3)) < sys.getsizeof([1, 2, 3]))On CPython this prints True. Don't choose a tuple for speed alone. The difference is rarely the bottleneck, and the signal about intent matters more.
Deciding when to use a tuple
The diagram shows a practical way to choose a container for grouped data.
Good uses of a plain tuple:
- Returning several values from a function. The function returns one tuple, and the caller can take it apart.
- Coordinates and other small fixed-shape values, such as
(x, y)or(r, g, b). - Dictionary keys or set members that combine several values, such as
(row, column)or(first_name, last_name). - Constant data that should not change, such as
WEEKEND = ("Sat", "Sun"). - Rows from a database or CSV reader when you treat each row as a record.
Poor uses of a plain tuple:
- A collection you plan to extend. Use a list.
- A record with many fields, such as eight or ten. Nobody remembers that
user[6]is the postal code. Use a named tuple, a dataclass or a dictionary. - Data you need to edit field by field. Each edit would force you to rebuild the whole tuple.
A function that returns a tuple looks like this:
def min_max(values):
return min(values), max(values)
result = min_max([3, 1, 4, 1, 5])
print(result)
print(type(result))
print(result[0], result[1])The output is (1, 5), then <class 'tuple'>, then 1 5. The return line has no parentheses, but the comma still builds a tuple. Callers usually split it into separate names, which is the topic of the unpacking chapters.
Gotchas to watch for
- Parentheses are not what makes a tuple. The commas do.
(3)is just the number 3, and(3,)is a tuple with one item. The next chapter covers this. - A tuple of mutable objects can still change.
([1, 2], 3)is a tuple, but the list inside it can grow. Such a tuple is also unhashable. +=on a tuple creates a new object. If another name refers to the old tuple, that name does not see the change. Lists behave differently, because+=extends a list in place.- Comparison is element by element.
(1, 2) < (1, 3)isTrue, because Python compares the first items, then the second. This lets you sort a list of tuples by their first field and then break ties with later ones.
people = [("Linus", 28), ("Ada", 36), ("Grace", 36), ("Ada", 30)]
print(sorted(people))This prints [('Ada', 30), ('Ada', 36), ('Grace', 36), ('Linus', 28)]. Python sorts by name first, and uses age to order the two Ada entries.
Summary of the working model
A tuple is one value made of a fixed number of positions. Its identity comes from its length and its contents, so two tuples with equal contents compare equal. Choose it when the group is small, its shape is fixed, and each position has its own meaning. Choose a list when the group is a growing collection. Choose a named tuple or a class when the positions need names.
Exercise
You are storing the position of a chess piece as (row, column) and you want to record which squares have already been visited in a set. Would you use a tuple or a list for each position, and why?
Show answer
Use a tuple. Set members must be hashable. A tuple of two integers is hashable, so (row, column) can go in a set. A list is mutable and unhashable, so adding it to a set raises TypeError. The position also has a fixed shape of two parts, which is what a tuple is for.
Exercise
What does this code print, and why? t = (1, 2, 3) t = t + (4,) print(t) t[0] = 99
Show answer
The first print shows (1, 2, 3, 4). The expression t + (4,) builds a new tuple and the name t is rebound to it. The line t[0] = 99 then raises TypeError: 'tuple' object does not support item assignment, because a tuple does not allow item assignment.