Python Tuples: Immutable Ordered Collections
What you’ll learn
Section titled “What you’ll learn”- How to create tuples, including the single-element gotcha that catches every newcomer.
- How unpacking assigns tuple elements to variables in one statement, and how the star operator captures the rest.
- Why tuples work as dictionary keys while lists do not, and what “hashable” means in practice.
- How
namedtuplegives readable, immutable records that still behave like tuples. - When to choose a tuple over a list, and when a list or a dataclass is the better fit.
- The crucial distinction between a tuple being immutable and the objects it holds being immutable.
Tuples are Python’s fixed, ordered, immutable sequences. Where a list says “this collection changes,” a tuple says “these values belong together and stay together.” That guarantee is small but it does real work: it lets tuples serve as dictionary keys, signals intent to other programmers, and protects records from accidental edits. This tutorial builds tuples for an OrdersPortal order-management system and shows where each form earns its place.
Prerequisites
Section titled “Prerequisites”- Python 3.9 or later. Run
python --versionto confirm the version. - Save examples as
tuples_demo.pyand runpython tuples_demo.py. Every complete sample prints its output. - Read Lists first, since tuples share list syntax for indexing, slicing, and iteration. The differences are about mutability, not access.
Tuples appear constantly in Python even when you do not write them explicitly. A function that returns return x, y returns a tuple. Iterating over dict.items() yields tuples. Understanding the type explains why those return values behave the way they do.
Step 1 — Create tuples
Section titled “Step 1 — Create tuples”A tuple is an ordered, immutable sequence. You build it with commas, usually inside parentheses. An empty tuple uses (). The single-element case is the gotcha that defines this step: the comma, not the parentheses, makes the tuple.
# a pair of coordinatespoint = (3, 7)
# parentheses are optional in many contextsorder = 1023, "Acme", 42.5
# empty and one-item tuplesempty = ()one = (1023,) # the trailing comma makes it a tuple, not an intnot_a_tuple = (1023)
print(type(point), type(one), type(not_a_tuple))# <class 'tuple'> <class 'tuple'> <class 'int'>The trailing comma is what creates the tuple, which is why (1023,) is a one-element tuple while (1023) is just the integer 1023 wrapped in grouping parentheses. Once you know this, the rule is easy, but it surprises everyone the first time.
Verify: print (1023) and (1023,) separately with type(). The first reports <class 'int'>; the second reports <class 'tuple'>. Try a two-element tuple without parentheses, 1023, "Acme", to confirm the comma is doing the work.
Step 2 — Access and unpack
Section titled “Step 2 — Access and unpack”Tuples support indexing and slicing like lists, and the result of a slice is itself a tuple. Unpacking is the feature that makes tuples expressive: one statement assigns each element to a named variable, and the classic swap becomes a single line.
order = (1023, "Acme", 42.5, "shipped")
# indexingprint(order[0]) # 1023print(order[-1]) # 'shipped'
# slicing returns a tuple, not a single valueprint(order[1:3]) # ('Acme', 42.5)
# unpackingorder_id, customer, amount, status = orderprint(customer, amount) # Acme 42.5
# ignore the rest with star-unpackingorder_id, *_ = orderprint(order_id) # 1023Unpacking removes the need to index into a fixed-shape return value, which is why so many Python functions return tuples. The star form, *_, collects the remaining elements into a list, so you can grab the first field and discard the rest.
Verify: swap two variables with a, b = b, a and print them. Then unpack with first, *rest = order and confirm rest is the list ['Acme', 42.5, 'shipped'].
Step 3 — Use a tuple as a dictionary key
Section titled “Step 3 — Use a tuple as a dictionary key”A tuple is hashable when every element is hashable, so it can serve as a dictionary key. Lists cannot, because they are mutable and a change would break the lookup. This is the most common reason to reach for a tuple in real programs: a compound key built from several values.
# track totals per (customer, region)totals = {}totals[("Acme", "West")] = 1500.0totals[("Acme", "East")] = 800.0totals[("Globex", "West")] = 3200.0
print(totals[("Acme", "West")]) # 1500.0print(("Globex", "West") in totals) # TrueCompound keys show up whenever you group data by more than one attribute. A pair of strings is hashable and immutable, so it makes a stable key even when the same customer appears in several regions.
Verify: try totals[["Acme", "West"]] = 1.0. Python raises TypeError: unhashable type: 'list', which is the language enforcing the rule that dictionary keys must not change after insertion.
Step 4 — Choose a tuple over a list
Section titled “Step 4 — Choose a tuple over a list”Use a tuple for fixed collections that should not change: coordinates, RGB colors, the set of valid status codes. Use a list when you will append, remove, or reorder. The choice communicates intent, and it also affects correctness, because a tuple will refuse the mutation that a list would silently accept.
# a tuple signals "these belong together and will not change"order_status_codes = ("pending", "paid", "shipped", "refunded")
# a list signals "this collection grows and shrinks"open_orders = [1023, 1024, 1025]open_orders.append(1026)There is a small performance benefit too: tuples are slightly lighter in memory than lists of the same length, and the interpreter can sometimes optimize them as constants. The real payoff, though, is safety and clarity, not speed.
Verify: call order_status_codes.append("canceled"). You get AttributeError, which is the tuple refusing mutation — exactly the protection you wanted when you chose the type.
Step 5 — Reach for namedtuple for readable records
Section titled “Step 5 — Reach for namedtuple for readable records”collections.namedtuple gives tuples named fields. The instances stay immutable and hashable, but code reads as order.customer instead of order[1], which matters the moment a record has more than two fields. A named tuple is still a tuple, so indexing and unpacking keep working.
from collections import namedtuple
Order = namedtuple("Order", ["order_id", "customer", "amount"])
o = Order(order_id=1023, customer="Acme", amount=42.5)print(o.customer) # 'Acme' — by nameprint(o[1]) # 'Acme' — by index still worksprint(o._asdict()) # {'order_id': 1023, 'customer': 'Acme', 'amount': 42.5}The _asdict() method returns a dictionary view of the fields, handy for serialization. Because a named tuple is a real tuple, you can unpack it and use it as a dict key, which a plain class cannot do.
Verify: try o.amount = 99. It raises AttributeError, confirming that named tuples preserve the immutability that makes tuples useful. If you need mutable fields, a dataclass is the right tool instead.
Step 6 — Understand shallow immutability
Section titled “Step 6 — Understand shallow immutability”A tuple is immutable, but “immutable” means you cannot rebind its elements, not that the objects it holds cannot change. If a tuple contains a list, the tuple’s slot is fixed, but the list inside it can still grow. This distinction is the source of the most subtle tuple bug.
# the tuple cannot be reassigned...t = (1023, ["Acme", "Globex"])# t[0] = 1024 # TypeError: tuple does not support item assignment
# ...but the list inside it can changet[1].append("Initech")print(t) # (1023, ['Acme', 'Globex', 'Initech'])The tuple is immutable at the level of its references; the targets of those references are free to mutate. This is shallow immutability, and it is why a tuple holding a list is not a safe dictionary key: the list’s contents can change, which would corrupt the hash.
Verify: call hash(t) on the tuple above. It raises TypeError: unhashable type: 'list', confirming that a tuple is only hashable when every element is hashable.
Complete working example
Section titled “Complete working example”This script models OrdersPortal orders with a namedtuple, groups them by a tuple key, and unpacks the keys for a readable report. It combines creation, hashing, unpacking, and named fields into one program.
from collections import namedtuple
Order = namedtuple("Order", ["order_id", "customer", "region", "amount"])
orders = [ Order(1023, "Acme", "West", 1500.0), Order(1024, "Acme", "East", 800.0), Order(1025, "Globex", "West", 3200.0), Order(1026, "Acme", "West", 450.0),]
# group amounts by (customer, region) using a tuple keytotals = {}for o in orders: key = (o.customer, o.region) totals[key] = totals.get(key, 0) + o.amount
# unpack the keys for a readable reportfor (customer, region), total in totals.items(): print(f"{customer} / {region}: ${total:,.2f}")Expected output:
Acme / West: $1,950.00Acme / East: $800.00Globex / West: $3,200.00The loop header, for (customer, region), total in totals.items(), unpacks two levels at once: the tuple key becomes two names, and the value becomes a third. That one line is the clearest argument for why tuples and unpacking belong together.
Troubleshooting
Section titled “Troubleshooting”Real error messages and their fixes, drawn from the mistakes that surface when you use tuples in a real program.
TypeError: tuple does not support item assignment— you tried to mutate a tuple element. Rebuild the tuple, or switch to a list if mutation is a real requirement.TypeError: unhashable type: 'list'— you used a list as a dictionary key or set member, or a tuple containing a list. Convert the list to a tuple, or restructure so the key contains only hashable types.ValueError: too many values to unpack— the tuple has more elements than your unpacking lists. Add a star expression,a, *rest = t, to absorb the extras.AttributeError: can't set attribute— you tried to assign to anamedtuplefield. Named tuples are immutable; create a new instance with the changed value, or use a dataclass.
Common mistakes
Section titled “Common mistakes”- Writing
(value)and expecting a tuple. A trailing comma is required:(value,). Without it the parentheses just group an expression and the result is the value itself. - Confusing tuple immutability with deep immutability. A tuple holding a list cannot be reassigned, but the inner list can still change. The tuple is immutable; its references’ targets are not.
- Using a tuple where you need to mutate. If the collection grows or shrinks, reach for a list. A tuple forces you to rebuild it, which is verbose and slow for frequent changes.
- Forgetting that multiple-return values are tuples.
x = 1, 2makesxa tuple even with no parentheses, andreturn a, breturns a tuple. Read carefully when a function hands back more than one value. - Picking
namedtupleoverdataclassfor records with defaults or methods.namedtupleis immutable and offers no default values without extra syntax. A frozen dataclass is usually clearer; see dataclasses. - Assuming a tuple key is always safe. A tuple is hashable only when every element is hashable. A tuple of strings is a fine key; a tuple containing a list is not.
Next steps
Section titled “Next steps”- Compare tuples with mutable ordered collections in Lists and Dictionaries.
- For richer immutable records, read dataclasses and the namedtuple feature page.
- When ordering matters and you need efficient appends and pops from both ends, see the collections module and deque.
Official references
Section titled “Official references”- Python 3 — Tuple Types — the built-in tuple type and its operations.
- Python 3 —
collections.namedtuple— factory for named tuple subclasses. - Python 3 — Hashable — the glossary entry that explains dictionary keys.
- PEP 8 — When to use a tuple — the style guide’s note on sequences that do not change.