namedtuple & NamedTuple
Published by Brayan K
A namedtuple is an immutable, tuple-based record whose positions have readable names, so you can write point.x instead of the cryptic point[0].
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Give positions names without losing tuple behaviour
A coordinate pair is easy to pass around, but point[1] makes the reader remember what position one means. namedtuple() builds a new tuple subclass with named fields. Call that class to create a record; calling the factory and creating a record are separate operations.
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
# Point is the new class; home is one record of that class.
home = Point(x=3, y=4)
print(home)
print(home.x, home[1])
x, y = home
print(x + y)
print(isinstance(home, tuple))
# ✅ Expected output:
# Point(x=3, y=4)
# 3 4
# 7
# TrueBoth position and field name read the same stored value. Positional arguments follow the field order declared in the factory, even when a caller thinks of the fields in another order. Keywords make a call with several similar values easier to check.
Comma syntax, indexing and ordinary tuple unpacking belong to Tuples. This lesson adds record names, generated helpers and the limits of a tuple-shaped data model.
Replacing a field makes another record
Named fields are read-only tuple positions. Assigning a different coordinate does not update the record:
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
home = Point(3, 4)
home.x = 9
# ✅ Expected error:
# AttributeError: can't set attributeUse _replace() and keep the returned record. The leading underscore is intentional: named-tuple helpers use it to avoid colliding with your field names. These documented helpers are public APIs.
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
home = Point(3, 4)
moved = home._replace(x=9)
print(home)
print(moved)
print(home is moved)
# ✅ Expected output:
# Point(x=3, y=4)
# Point(x=9, y=4)
# FalseIgnoring the returned value leaves your variable pointing at the original. A named tuple is not deeply immutable, however: a field can refer to a mutable object. The field still points at the same list when the list changes.
from collections import namedtuple
Basket = namedtuple("Basket", ["owner", "items"])
items = ["tea"]
basket = Basket("Mina", items)
items.append("milk")
print(basket.items)
print(basket.items is items)
# ✅ Expected output:
# ['tea', 'milk']
# TrueUse a tuple inside the record when the nested collection should also be immutable. Whether a record can be a dictionary key depends on all its field values being hashable; naming the fields does not make a list hashable.
Tuple equality does not distinguish record types
A named tuple compares its values by position, just like a tuple. It can compare equal to a plain tuple or a different named-tuple class whose fields have different meanings. Field names are not part of this equality test.
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
Size = namedtuple("Size", ["width", "height"])
location = Point(3, 4)
size = Size(3, 4)
print(location == (3, 4))
print(location == size)
print(type(location) is type(size))
# ✅ Expected output:
# True
# True
# FalseThis is useful for compatibility with tuple-returning APIs, but unsafe to interpret as proof that two records mean the same thing. A default dataclass compares equal only to the same dataclass type. Choose a dataclass when distinct record identity, mutable fields or more involved initialization is the desired model.
Data Classes & Advanced Class Patterns owns dataclass generation, defaults and validation hooks. Named tuples here deliberately retain tuple behaviour.
Defaults fill the rightmost fields, not any missing field
The factory takes defaults for the final fields in declaration order. In a two-field record with one default, only the second field is optional. A required first field does not become optional just because the call supplies the second by keyword.
from collections import namedtuple
Item = namedtuple("Item", ["name", "quantity"], defaults=[1])
print(Item("tea"))
print(Item("tea", quantity=3))
print(Item._field_defaults)
# ✅ Expected output:
# Item(name='tea', quantity=1)
# Item(name='tea', quantity=3)
# {'quantity': 1}from collections import namedtuple
Item = namedtuple("Item", ["name", "quantity"], defaults=[1])
Item(quantity=3)
# ✅ Expected error:
# TypeError: Item.__new__() missing 1 required positional argument: 'name'Repair the call by providing a name. Avoid a shared mutable default such as a list: every record that omits that field would refer to the same list. A named-tuple default is a value, not a factory that runs for every record.
Move between rows, records and dictionaries explicitly
_make(iterable) creates a record from a row containing exactly the right number of values. _asdict() returns a new dictionary with field names as keys, in field order. _fields reports that order so you can check a producer before interpreting its rows.
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
row = [3, 4]
location = Point._make(row)
mapping = location._asdict()
mapping["x"] = 99
print(Point._fields)
print(location)
print(mapping)
# ✅ Expected output:
# ('x', 'y')
# Point(x=3, y=4)
# {'x': 99, 'y': 4}Changing the new dictionary does not reassign a field in the original record. This is a shallow conversion: a nested list would still be shared. A row of the wrong length is rejected before a record is returned:
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
Point._make([3])
# ✅ Expected error:
# TypeError: Expected 2 arguments, got 1Field names must be valid Python identifiers, cannot start with an underscore, and cannot repeat. Validate or deliberately rename external column headings before treating them as attributes; blindly deriving a record class from a CSV header is not validation of that file.
NamedTuple adds hints, not runtime conversion
typing.NamedTuple lets a class declaration describe the same kind of tuple record with type hints. Defaults still follow required fields. A method can use the fields, but the annotations do not check or convert arguments at runtime.
from typing import NamedTuple
class Item(NamedTuple):
name: str
quantity: int = 1
good = Item("tea", 3)
wrong = Item("tea", "3")
print(good.quantity * 2)
print(wrong.quantity * 2)
print(type(wrong.quantity).__name__)
# ✅ Expected output:
# 6
# 33
# strThe wrong quantity is accepted by the constructor and string repetition happens later. The independent exercise therefore converts and validates incoming data before building a record. A static checker can flag the incompatible constructor call, but that checker is separate from running Python.
Type Hints & Static Typing with MyPy owns static checking and annotation evaluation. Advanced Collections, Itertools & Functools delegates named-tuple records to this lesson and covers other collection tools.
Complete a corrected stock record
Build a record with its default quantity, replace the quantity and print the corrected value. Keep the original visible to prove the replacement did not mutate it.
from collections import namedtuple
Item = namedtuple("Item", ["name", "quantity"], defaults=[1])
original = ___("tea")
# 👉 replace ___ with Item
corrected = original.___(quantity=4)
# 👉 replace ___ with _replace
print(original.quantity)
print(corrected.___)
# 👉 replace ___ with quantity
# ✅ Expected output:
# 1
# 4Validate incoming stock before making records
Define a NamedTuple called Stock with name: str and quantity: int. Read the rows [("tea", "3"), ("milk", "-1"), ("coffee", "two")]. Convert each quantity with int, reject negatives with ValueError("quantity must be nonnegative"), and print accepted records and rejected item names. Keep conversion and validation outside the record class.
from typing import NamedTuple
class Stock(NamedTuple):
name: str
quantity: int
def parse_stock(name, raw_quantity):
quantity = int(raw_quantity)
if quantity < 0:
raise ValueError("quantity must be nonnegative")
return Stock(name, quantity)
accepted = []
rejected = []
for name, raw in [("tea", "3"), ("milk", "-1"), ("coffee", "two")]:
try:
item = parse_stock(name, raw)
except ValueError:
rejected.append(name)
else:
accepted.append(item)
print(accepted)
print("rejected:", rejected)
# ✅ Expected output:
# [Stock(name='tea', quantity=3)]
# rejected: ['milk', 'coffee']The NamedTuple describes the accepted shape; the parser enforces this input contract. A direct call to Stock can still bypass the parser, so keep untrusted data entering through the validated boundary.
Practice quiz
What does this program print? from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) print(Point(2, 5).y)
- 2
- 5
- Point
- 1
Answer: 5. The y field is the second stored position.
What does this program print? from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) p = Point(2, 5) q = p._replace(y=9) print(p.y, q.y)
- 9 9
- 5 5
- 9 5
- 5 9
Answer: 5 9. _replace returns a new record and leaves p unchanged.
What does this program print? from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) print(Point(2, 5) == (2, 5))
- True
- False
- TypeError
- None
Answer: True. Named-tuple equality retains positional tuple equality.
What does this program print? from collections import namedtuple Item = namedtuple("Item", ["name", "qty"], defaults=[1]) print(Item("tea").qty)
- 0
- None
- 1
- TypeError
Answer: 1. A single default fills the rightmost field, qty.
What does this program print? from typing import NamedTuple class Count(NamedTuple): value: int print(type(Count("4").value).__name__)
- int
- str
- Count
- TypeError
Answer: str. The annotation neither converts nor rejects the string at runtime.
What does this program print? from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) p = Point._make([2, 5]) print(list(p._asdict()))
- ['2', '5']
- [2, 5]
- ['Point']
- ['x', 'y']
Answer: ['x', 'y']. The new dictionary uses field names in declaration order.
A record has a list field. What does tuple immutability prevent?
- Reassigning the field to a different list.
- Appending to the existing list.
- Another name reading the same list.
- The list containing more than one item.
Answer: Reassigning the field to a different list.. The tuple slot is read-only; the object referenced by that slot can still mutate.
Which design is the better fit when equality must distinguish two record classes and fields must be mutable?
- A named tuple with different field names.
- A plain tuple.
- A dataclass with its default equality and mutable fields.
- Calling _asdict() before every comparison.
Answer: A dataclass with its default equality and mutable fields.. Default dataclass equality requires the same class; ordinary dataclass fields can be reassigned.
Continue this course
- Previous: Enums (the enum module)
- Next: Randomness with the random Module — randint, choice, shuffle and seeded reproducibility (and when to use secrets)
- Quick reference: Python cheat sheet