8. Python Tuples
Python Tuples
A tuple is an ordered, immutable collection of items. It looks almost identical to a list but with one fundamental difference: once a tuple is created, its contents cannot be changed. You cannot add, remove, or modify items.
This immutability is not a limitation — it is a deliberate design choice. Tuples are used when you have a fixed collection of related values that should never change: coordinates, RGB colors, database records, function return values. Their immutability makes them faster than lists and safe to use as dictionary keys.
Creating a Tuple
Tuples are created using parentheses, with items separated by commas. There is one critical rule: a tuple with a single item must have a trailing comma — without it, Python interprets the parentheses as just grouping, not a tuple.
Accessing Items
Tuples use the exact same zero-based indexing as lists. Access items using square brackets with the index number.
Negative Indexing
Just like lists, tuples support negative indexing to count from the end. -1 is the last item, -2 is second-to-last.
Slicing
Tuples support the same slice syntax as lists — tuple[start:end] — and return a new tuple containing the selected items.
Immutability Explained
Tuples are immutable — you cannot change, add, or remove items after creation. Attempting to do so raises a TypeError. This is intentional: use a tuple when data should be treated as a fixed, read-only record.
- Tuples are faster than lists for iteration — Python can optimise immutable sequences
- Tuples can be used as dictionary keys; lists cannot (because lists are mutable)
- Tuples signal intent — when a teammate sees a tuple, they know that data should not change
Update Workaround
Since tuples are immutable, you cannot modify them directly. The standard workaround is to convert the tuple to a list, make your changes, then convert back to a tuple.
Notice that the original tuple is completely untouched. The updated variable holds an entirely new tuple object. This is the correct and Pythonic way to "modify" a tuple.
Unpacking
Tuple unpacking lets you assign each item in a tuple to a separate variable in a single clean line. The number of variables on the left must match the number of items in the tuple.
Looping Through a Tuple
You can iterate through a tuple using a for loop exactly as you would a list. Use enumerate() when you also need the index of each item.
Joining Tuples
You can combine two tuples using the + operator, which creates a new tuple containing all items from both. The original tuples remain unchanged.
Tuple Methods
Because tuples are immutable, they only have two built-in methods: .count() and .index(). All the mutating methods lists have (.append, .remove, etc.) simply do not exist on tuples.
.index(value) raises a ValueError if the value does not exist in the tuple. To safely check first, use value in my_tuple before calling .index().
Knowledge Check
Ready to test your understanding of 8. Python Tuples?