Tuples & Sequence Unpacking
Explore immutable sequences, sequence unpacking, memory optimization, and how tuples provide tamper-proof keys for dictionaries.
Immutable Sequences
A tuple is an ordered, immutable collection of elements. Unlike lists, once a tuple is constructed in memory, its size and its element pointers cannot be added, removed, or reassigned.
Tuples are syntactically created using commas, often enclosed in parentheses: point = (10, 20). The comma is what actually defines the tuple, not the parentheses.
Because tuples have fixed lengths, CPython optimizes their memory allocation. Tuples consume less RAM than lists and can be cached internally via small-tuple free lists for instantaneous reuse.
Data Integrity & Hashable Keys
Use tuples when you want to signal that a sequence represents a fixed record with constant fields (like GPS coordinates (lat, lon) or an RGB color (255, 128, 0)).
Because tuples are immutable, they are hashable - provided that every element inside the tuple is also hashable. This means tuples can serve as dictionary keys or set elements, whereas lists cannot.
If a tuple contains an internal mutable object (like a list: t = (1, [2, 3])), the tuple itself becomes unhashable and cannot be used as a dictionary key.
Sequence Unpacking & Starred Expressions
Python allows elegant sequence unpacking: x, y = (10, 20) directly assigns 10 to x and 20 to y in a single statement.
This unlocks Python's famous variable swap idiom: a, b = b, a. Python packs the right-hand values into a temporary tuple and unpacks them into the left-hand targets atomically, with no need for a temporary intermediate variable.
Extended unpacking (PEP 3132) uses an asterisk * to capture leftover elements into a list: first, *middle, last = (1, 2, 3, 4, 5). Here, first is 1, middle becomes [2, 3, 4], and last is 5.
The Immutability & Unpacking Console
Test tuple operations. Attempt an illegal in-place mutation to inspect the immutability shield, and execute variable swaps and starred unpacking.
Python Rule: Commas define tuples, not parentheses. When defining a 1-item tuple, always write item, or (item,).
Tuples are immutable. Once created, element pointers cannot be reassigned. Attempting assignment raises TypeError.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Tuples are immutable sequences: elements cannot be added, removed, or reassigned.
- The comma defines a tuple, not parentheses: (42,) is a tuple, but (42) is an int.
- Tuples are hashable and valid dictionary keys only if all their elements are hashable.
- Atomic variable swap (a, b = b, a) works by tuple packing and unpacking without temp variables.
- Extended unpacking (first, *rest, last) gathers intermediate values into a list.
Done with this concept?
Mark it complete to track your progress. No login needed.