namedtuple & NamedTuple
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].
Learn namedtuple & NamedTuple in our free Python course — an interactive lesson with runnable examples, a practice exercise and a quick reference.
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.
They are the fastest way to replace a confusing tuple like (40.7, -74.0) with a self-documenting record you can pass around, unpack, and use as a dictionary key.
namedtuple is a factory: you give it a type name and a list of field names, and it returns a new class. Instances behave like tuples but also expose each position by name:
Because a namedtuple is a real tuple, anything that accepts a tuple accepts it — including being a dictionary key or a set element. You gain readable names for free.
You cannot reassign a field — that is the point. To "change" one, you create a fresh copy with _replace . The underscore-prefixed methods are public API (the underscore just avoids clashing with your field names):
The class-based form reads like a normal class, adds type annotations, supports default values, and even lets you define methods. It is the modern, recommended way:
It is still a real tuple under the hood, so _replace , _asdict , _fields , indexing, and unpacking all work exactly as before — you just get cleaner syntax, defaults, and type hints on top.
Complete the namedtuple so it builds a record and produces a changed copy. Replace each ___ and match the expected output.
Method blank: _replace — it returns a new copy with the updated field.
❌ Putting a default field before a required one (class form)
✅ List required fields first, defaulted fields last.
Use a NamedTuple to model 2D points, then compute the distance between two of them and shift one along the x-axis.
Go deeper with the official Python documentation:
Lesson complete — your tuples have names now!
You can build records with collections.namedtuple , access fields by name and index, copy immutably with _replace , inspect with _asdict and _fields , and use the cleaner typing.NamedTuple class form with defaults and methods.
🚀 Up next: Randomness with random — generate numbers, shuffle, and sample reproducibly.
Practice quiz
What is a namedtuple?
- A mutable dictionary
- A list with a name
- A tuple subclass whose positions also have names
- A frozen set
Answer: A tuple subclass whose positions also have names. A namedtuple is a tuple subclass that adds readable names to its positions.
Given Point = namedtuple('Point', ['x', 'y']) and p = Point(3, 4), what does p.x equal?
- 3
- 4
- (3, 4)
- None
Answer: 3. p.x accesses the first field, which is 3.
Can you still access a namedtuple by index, e.g. p[1]?
- No, only by name
- Only with _get
- Only if frozen
- Yes, it behaves like a tuple
Answer: Yes, it behaves like a tuple. A namedtuple is a real tuple, so indexing like p[1] still works.
What happens when you try p.x = 10 on a namedtuple?
- It updates x
- It raises an AttributeError
- It returns a copy
- It returns None
Answer: It raises an AttributeError. Namedtuples are immutable, so assigning to a field raises AttributeError.
What does p._replace(x=10) do?
- Returns a NEW namedtuple with x=10, leaving p unchanged
- Mutates p in place
- Deletes x
- Raises an error
Answer: Returns a NEW namedtuple with x=10, leaving p unchanged. _replace returns a fresh copy with the field changed; the original stays the same.
What does p._asdict() return for Point(3, 4)?
- (3, 4)
_asdict() converts the namedtuple into a plain dict of its fields.
What does Point._fields return?
- (3, 4)
- ('x', 'y')
- x
- y
Answer: ('x', 'y'). _fields is a tuple of the field names: ('x', 'y').
In the typing.NamedTuple class form, where must fields WITH defaults go?
- First
- Anywhere
- Only in __init__
- After fields without defaults
Answer: After fields without defaults. Like default function arguments, defaulted fields must come after non-default ones.
A key advantage of typing.NamedTuple over collections.namedtuple is that it...
- Is mutable
- Supports type annotations, defaults, and methods in clean class syntax
- Runs faster
- Has no field names
Answer: Supports type annotations, defaults, and methods in clean class syntax. The class form adds type hints, default values, and methods with readable syntax.
When should you prefer a dataclass over a namedtuple?
- When you need a tuple-like immutable record
- When you want dict keys
- When you need mutability, many methods, or inheritance
- When you want unpacking
Answer: When you need mutability, many methods, or inheritance. Namedtuples are light and immutable; dataclasses suit mutability and richer behavior.