Tuples & The NamedTuple
A Tuple is an ordered, immutable sequence of objects. While they often look like “restricted lists,” tuples serve a fundamentally different purpose in software design.
In Python, Lists are for collections of similar items (homogeneity), while Tuples are for collections of different pieces of data that belong together as a single record (heterogeneity).
1. Defining Tuples
Section titled “1. Defining Tuples”Tuples are defined using parentheses () or simply by separating items with commas (Packing).
# Standard definitionpoint = (10, 20)
# Tuple Packingrecord = "Alice", 30, "Developer"
# The Single-Item Trapnot_a_tuple = (5) # This is just the integer 5is_a_tuple = (5,) # The trailing comma is REQUIRED for single-item tuplesImmutability: The Contract of Integrity
Section titled “Immutability: The Contract of Integrity”Once a tuple is created, you cannot change its size or its contents. This immutability provides Data Integrity: if you pass a tuple to a function, you can be 100% certain the function cannot modify your data.
2. Tuple Unpacking
Section titled “2. Tuple Unpacking”Unpacking is one of Python’s most elegant features, allowing you to assign tuple elements to variables in a single line.
# Basic Unpackingx, y = (10, 20)
# Extended Unpacking (The * operator)first, *middle, last = (1, 2, 3, 4, 5)# first = 1, middle = [2, 3, 4], last = 53. Self-Documenting Data: NamedTuples
Section titled “3. Self-Documenting Data: NamedTuples”A standard tuple like ("Alice", 30) is “blind”—you have to remember that index 0 is the name and index 1 is the age. NamedTuples solve this by allowing you to access fields by name.
Using collections.namedtuple
Section titled “Using collections.namedtuple”from collections import namedtuple
# Define the "Class"User = namedtuple("User", ["name", "age", "role"])
# Create an instanceu = User(name="Bob", age=25, role="Admin")
print(u.name) # Access by name!print(u[0]) # Still works like a normal tupleUsing typing.NamedTuple (Modern & Typed)
Section titled “Using typing.NamedTuple (Modern & Typed)”In modern Python, we prefer the class-based syntax which allows for Type Hints.
from typing import NamedTuple
class Point(NamedTuple): x: int y: int
p = Point(x=10, y=20)4. Under the Hood: Why Tuples are Faster
Section titled “4. Under the Hood: Why Tuples are Faster”- Fixed Allocation: When a list is created, Python allocates extra space to allow for future
append()calls. When a tuple is created, Python allocates exactly the memory needed for the items. - No Dynamic Resizing: Tuples don’t need the overhead of checking if they need to grow.
- Caching: Python’s garbage collector doesn’t have to work as hard because tuples are simpler objects. Furthermore, small tuples are often cached by the interpreter for reuse.
5. Summary Table
Section titled “5. Summary Table”| Feature | List | Tuple |
|---|---|---|
| Mutability | Mutable (can change) | Immutable (cannot change) |
| Size | Dynamic (can grow) | Fixed (constant) |
| Performance | Slower | Faster |
| Use Case | Collections of same-type items. | Single records of mixed-type items. |
| Hashability | No (cannot be a dict key) | Yes (if contents are hashable) |