Python Tuples: Immutable Sequences and Unpacking
A tuple is an ordered sequence like a list, but it cannot be changed after it is created. You write it with commas, usually inside parentheses: point = (3, 4). Tuples suit small groups of values that belong together and have a fixed meaning by position, such as a coordinate, an RGB color, or a row returned from a database.
The comma makes the tuple
The parentheses are often optional; it is the comma that creates a tuple. rgb = 255, 128, 0 is a three-item tuple. The flip side is that (5) is just the number 5 in parentheses. A one-item tuple needs a trailing comma: (5,). An empty tuple is ().
Unpacking
Unpacking assigns each item of a sequence to its own name in a single statement: x, y = point. The number of names must match the number of items, otherwise Python raises ValueError. You already used unpacking for swapping in the variables chapter, and you will use it constantly in loops and when functions return several values.
Expected output
3 4 3 <class 'tuple'> <class 'int'> (255, 128, 0) 3 1 1 (3, 4, 5) [0, 128, 255]
What you can and cannot do
Indexing, slicing, len(), in, + and * all work, and each returns a new tuple. Tuples have only two methods: count(x) and index(x). Assigning to an item, as in point[0] = 10, raises TypeError: 'tuple' object does not support item assignment. There is no append or sort; sorted(rgb) still works because it builds a new list.
Tuple or list?
Choose a list for a collection of similar items whose length changes, like a shopping cart. Choose a tuple for a fixed-size record where each position has a meaning. Because tuples are immutable, a tuple of immutable values can also be used as a dictionary key or stored in a set, which lists cannot.
Common mistakes
- Writing
(5)and expecting a tuple; you need(5,). - Trying to modify a tuple. Build a new one instead, for example
point + (5,). - Unpacking the wrong number of items:
a, b = (1, 2, 3)raisesValueError.
Summary
- Tuples are ordered and immutable; commas create them.
- One-item tuples need a trailing comma.
- Unpacking assigns items to names in one line.
- Use tuples for fixed records and as dictionary keys.
Quiz: Tuples