Python Tutorial / Understand Tuples and Sequence Unpacking

A tuple is an ordered sequence whose item references cannot be replaced. It is useful for short records and multiple return values, but mutable objects stored inside a tuple can still change.

Create tuples and define the immutability boundary

The comma creates a tuple; parentheses make the grouping clearer. A one-item tuple needs a trailing comma, as in (3500,). By contrast, (3500) is an integer expression. If a tuple contains a list, the list’s contents remain mutable.

single = (3500,)
record = ("lunch", 8000)
print(type(single).__name__)
print(record[0])

The first line prints tuple and the second prints lunch. This verifies that the one-item form differs from an ordinary parenthesized number.

For the relevant APIs and platform requirements, see Python: datastructures.

Tuples as keys and data records build on the rules demonstrated in Store Key–Value Data with Dictionaries.

Run sequence unpacking

Save the complete code below as tuples.py in a separate practice folder, using UTF-8. Run python tuples.py in a terminal with your project virtual environment selected. Outside a virtual environment on macOS or Ubuntu, use python3 when that is your interpreter command.

record = ("lunch", 8000, "food")
name, amount, category = record
print(name, amount, category)
first, *rest = [3500, 8000, 2500]
print(first, rest)
a, b = 1, 2
a, b = b, a
print(a, b)

Expected output:

lunch 8000 food
3500 [8000, 2500]
2 1

Match the number and meaning of values

Unpacking into plain names requires the same number of items. A mismatch raises ValueError. A starred target receives the remaining items as a list; only one starred target can occur in a single unpacking assignment.

Iterating a dictionary directly produces keys. To unpack keys and values together, use items(). Check the shape of external file or network data before assuming that every record contains the same number of fields.

Tuple immutability prevents replacing its item references. With pair = ([1], 2), assigning pair[0] = [] fails, but pair[0].append(3) succeeds and leaves ([1, 3], 2). The referenced list remains mutable even though the tuple itself is immutable.

Choose between lists, tuples and named records

Need Suitable structure
An expanding sequence of amounts List
A small fixed-position record Tuple
Fields identified by meaningful names Dictionary or dataclass

A tuple can be a dictionary key only when all of its elements are hashable. A tuple containing a list is not hashable. Fixed outer structure does not establish that all nested data can serve as a key.

Remove category from the example record to observe unpacking failure, then adjust the target names to match. Restore the original record afterwards. When positional meanings become hard to remember, named fields may communicate the data model more clearly.