Create tuple-based records with named fields.
What You Will Learn
namedtuple(typename, field_names) builds a tuple subclass whose elements can be read by attribute or index. Instances remain immutable, though mutable values stored inside are not made immutable.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
point = Point(3, 8)
print(point.x)
print(point[1])
How the Example Works
- The imports provide the standard-library tools used in the demonstration: collections.
- The variable Point holds the result of namedtuple('Point', ['x', 'y']). Later lines use that value or inspect how it changes.
- The variable point holds the result of Point(3, 8). Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
Expected output from the example:
3
8
When You Would Use This
Decide which input types are valid, what output should be produced, and which cases should fail clearly. A small self-contained demonstration is a good starting point before adding file access, network calls, or application state.
Practice: Modify the Code
Represent a color with red, green, and blue named fields.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Expecting to assign point.x directly because the field has a readable name.
- Overlooking this documented constraint: instances remain immutable, though mutable values stored inside are not made immutable.
Key Takeaways
- Create tuple-based records with named fields.
- namedtuple(typename, field_names) builds a tuple subclass whose elements can be read by attribute or index.
- Apply this operation only after checking the assumptions and input conditions shown in the example.