Free Online Code Editor
Create tuple subclasses with named fields.
from collections import namedtuple
# Define namedtuple
Point = namedtuple("Point", ["x", "y"])
# Create instances
p1 = Point(1, 2)
p2 = Point(3, 4)
print(f"Point 1: {p1}")
print(f"X: {p1.x}, Y: {p1.y}")
# Access by index
print(f"\nBy index: {p1[0]}, {p1[1]}")
# Unpacking
x, y = p1
print(f"\nUnpacked: x={x}, y={y}")
# Practical example
Student = namedtuple("Student", ["name", "age", "grade"])
students = [
Student("Alice", 20, "A"),
Student("Bob", 22, "B"),
Student("Charlie", 21, "A")
]
print("\nStudents:")
for s in students:
print(f" {s.name}, {s.age} years, grade {s.grade}")
# Replace fields
p3 = p1._replace(x=10)
print(f"\nOriginal: {p1}")
print(f"Modified: {p3}")
# Convert to dict
print(f"\nAs dict: {p1._asdict()}")namedtuple creates tuple subclasses with named fields. Access by name or index. Memory efficient like tuples but more readable.