Tuples
A tuple is an ordered collection of items, just like a list, except that it cannot be changed after it is created. Use tuples for groups of values that belong together and shouldn't change, such as GPS coordinates, a date or an RGB colour.
Creating tuples
Write the items inside round brackets, separated by commas. Strictly speaking, it's the commas that make a tuple; the brackets are often optional but help readability.
nairobi = (-1.2921, 36.8219) # latitude, longitude birthday = (14, "March", 2004) colours = "red", "green", "blue" # brackets left out print(nairobi) print(colours) print(type(birthday))
The one-item tuple
A tuple with a single item needs a trailing comma. Without it, Python sees ordinary brackets around a value.
not_a_tuple = (5) single = (5,) print(type(not_a_tuple)) print(type(single)) print(single)
An empty tuple is written (), and tuple() converts other sequences: tuple([1, 2, 3]) gives (1, 2, 3).
Accessing items
Indexing, slicing, len(), in and for loops all work exactly as they do for lists.
birthday = (14, "March", 2004)
print(birthday[1])
print(birthday[-1])
print(birthday[:2])
print(len(birthday))
print("March" in birthday)
Tuples are immutable
Once a tuple exists, you can't replace, add or remove items. There is no append(), remove() or sort().
location = ("Nairobi", -1.2921, 36.8219)
location[0] = "Mombasa"
To "change" a tuple you create a new one, for example location = ("Mombasa",) + location[1:]. This immutability is a feature: it guarantees that data you meant to keep fixed can't be changed by accident somewhere else in your program.
A tuple can't change which items it holds, but if one of those items is mutable, such as a list, that list's contents can still change. For example, with t = ([1, 2], 3), running t[0].append(3) works and t becomes ([1, 2, 3], 3). Keep tuples to immutable values when you want them fully fixed.
Packing and unpacking
Putting values into a tuple is called packing; pulling them out into separate variables is unpacking. Unpacking is one of the most useful features in Python.
location = ("Nairobi", -1.2921, 36.8219) # packing
city, lat, lon = location # unpacking
print(city)
print(lat, lon)
Use * to collect "the rest" into a list:
first, *others = (90, 85, 72, 64) print(first) print(others)
Notice that the starred variable is always a list, even though the source was a tuple.
You have already used tuples without realising it. The variable swap a, b = b, a packs the right side into a tuple and unpacks it on the left. And when a loop gives you two values at once, as with enumerate() or a list of pairs, each item is a tuple being unpacked:
results = [("Amina", 78), ("Brian", 64), ("Chebet", 91)]
for name, score in results:
print(f"{name} scored {score}")
Unpacking into the wrong number of variables. a, b = (1, 2, 3) raises a ValueError about too many values to unpack. Use the same number of names as items, or add a starred name to collect the extras.
Tuple methods
Because they can't change, tuples have only two methods:
dice = (2, 5, 2, 6, 2) print(dice.count(2)) print(dice.index(6))
When to use a tuple instead of a list
| Tuple | List |
|---|---|
| Fixed group of related values | Collection that grows, shrinks or gets sorted |
| Items often mean different things: (name, age, county) | Items are usually the same kind: a list of names |
| Can be a dictionary key or set item (if its contents are immutable) | Can't be a dictionary key or set item |
| Slightly smaller and faster | Many methods for changing contents |
Functions often return several results as a tuple. You've seen divmod(17, 5) return (3, 2), and you'll write your own on Return Values. Tuples also make good keys in dictionaries, for example a pair of towns as the key for the distance between them.
Key points
- Tuples are ordered and immutable; create them with commas, usually inside round brackets.
- A one-item tuple needs a trailing comma:
(5,). - Indexing, slicing,
len(),inand loops work just like lists. - Unpacking (
a, b = pair) and starred unpacking (first, *rest) are powerful everyday tools. - Use tuples for fixed records and lists for collections that change.
Tip: use the ← and → keys to move between pages.
