Skip to content

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).


Tuples are defined using parentheses () or simply by separating items with commas (Packing).

syntax.py
# Standard definition
point = (10, 20)
# Tuple Packing
record = "Alice", 30, "Developer"
# The Single-Item Trap
not_a_tuple = (5) # This is just the integer 5
is_a_tuple = (5,) # The trailing comma is REQUIRED for single-item tuples

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.


Unpacking is one of Python’s most elegant features, allowing you to assign tuple elements to variables in a single line.

unpacking.py
# Basic Unpacking
x, y = (10, 20)
# Extended Unpacking (The * operator)
first, *middle, last = (1, 2, 3, 4, 5)
# first = 1, middle = [2, 3, 4], last = 5

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.

named_tuple.py
from collections import namedtuple
# Define the "Class"
User = namedtuple("User", ["name", "age", "role"])
# Create an instance
u = User(name="Bob", age=25, role="Admin")
print(u.name) # Access by name!
print(u[0]) # Still works like a normal tuple

In modern Python, we prefer the class-based syntax which allows for Type Hints.

typed_named_tuple.py
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
p = Point(x=10, y=20)

  1. 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.
  2. No Dynamic Resizing: Tuples don’t need the overhead of checking if they need to grow.
  3. 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.

FeatureListTuple
MutabilityMutable (can change)Immutable (cannot change)
SizeDynamic (can grow)Fixed (constant)
PerformanceSlowerFaster
Use CaseCollections of same-type items.Single records of mixed-type items.
HashabilityNo (cannot be a dict key)Yes (if contents are hashable)