SyntaxStudy
Sign Up
Python Intermediate 9 min read

Named Tuples

Named Tuples

Named tuples let you access tuple elements by name instead of index, making code much more readable without the overhead of a full class.

collections.namedtuple

from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])
p = Point(3, 7)
print(p.x)        # 3
print(p.y)        # 7
print(p[0])       # 3 (index still works)
print(p)          # Point(x=3, y=7)

Practical Example

Employee = namedtuple("Employee", "name age department salary")
emp = Employee("Alice", 30, "Engineering", 95000)
print(emp.name)           # Alice
print(emp._asdict())      # OrderedDict
emp2 = emp._replace(salary=100000)
print(emp2.salary)        # 100000

typing.NamedTuple (Modern)

from typing import NamedTuple

class Color(NamedTuple):
    red: int
    green: int
    blue: int
    alpha: float = 1.0

c = Color(255, 128, 0)
print(c.red)    # 255
print(c.alpha)  # 1.0 (default)
Example
from collections import namedtuple

Card = namedtuple("Card", ["rank", "suit"])
hand = [Card("A", "spades"), Card("K", "hearts"), Card("10", "clubs")]

for card in hand:
    print(f"{card.rank} of {card.suit}")

print(hand[0]._asdict())
Pro Tip

Named tuples are still immutable tuples under the hood — use _replace() to create a modified copy, similar to how you would with a frozen dataclass.