A shipment row contains a product name, price and quantity.
What You Need to Understand
collections.namedtuple() creates tuple-like records with readable field names. Instances preserve tuple behavior while letting you access attributes instead of remembering numeric positions.
When to Use It
A shipment row contains a product name, price and quantity.
Step-by-Step Python Example
from collections import namedtuple
Product = namedtuple("Product", ["name", "price", "quantity"])
item = Product("Pencil", 1.5, 4)
print(item.name)
print(item.price * item.quantity)
How the Example Works
The generated record can be unpacked like a tuple, but item.name makes code easier to understand.
Example Output
Pencil
6.0
3
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
from collections import namedtuple
Point = namedtuple("Point", "x y")
print(Point(3, 4).x)
Important Behavior and Edge Cases
Named tuples are immutable at the top level; editing a field requires creating a replacement. For more complex records consider a dataclass.
Try It Yourself
Create a named tuple named Point with fields x and y.
Common Beginner Mistakes
- Named tuples are immutable at the top level; editing a field requires creating a replacement. For more complex records consider a dataclass.
- Assuming every sequence operation modifies the original data or that a tuple makes nested mutable objects immutable.
Key Takeaways
collections.namedtuple()creates tuple-like records with readable field names.- The generated record can be unpacked like a tuple, but
item.namemakes code easier to understand. - Named tuples are immutable at the top level; editing a field requires creating a replacement.