namedtuple
- Python course
- Intermediate
- Lesson 92/116
- 4 min
Learn named tuples with namedtuple.
namedtuple
A namedtuple is immutable like a tuple but its fields can be accessed by name. It comes from the collections module; it is ideal for small, immutable data structures.
Example: Point = namedtuple("Point", ["x", "y"]). This produces a class; you create an instance with p = Point(3, 4). You access fields by name with p.x and p.y; or by index with p[0] and p[1]. It is immutable like a tuple; you cannot write p.x = 5.
When to use it?
namedtuple is ideal for small, immutable data sets. Example: a point, a coordinate, a color (RGB). When a dataclass would be too heavy and only a few fields are needed, namedtuple is lighter.
It is hashable like a tuple; it can be a dictionary key. len(p) gives the field count. With p._asdict() you can convert it to a dict. Memory usage is lower than a normal class.
Practice Define the Point namedtuple
Start with from collections import namedtuple. Produce a namedtuple with Point = namedtuple("Point", ["x", "y"]). Create an instance with p = Point(3, 4) and print with print(p.x, p.y).
Starter code
# Define the Point namedtupleSample solution
# Define the Point namedtuple
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y)Expected output
3 4
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How does namedtuple allow access?
- Only by index
- Only by name
- Both by name and index Correct answer
- Only by method
Explanation: namedtuple supports both.
2 namedtuple definition
from collections import namedtuple
Point = ____("Point", ["x", "y"])
p = Point(3, 4)
print(p.x)
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x)
Explanation: The namedtuple function produces a new class.
3 Match the namedtuple parts
| Term | Meaning |
|---|---|
namedtuple |
Function |
Point |
Produced class |
p.x |
Access by name |
p[0] |
Access by index |