Named tuples are one of my favourite data structures in Python, especially for Advent of Code style puzzles. They provide a semantic wrapper with a name, named properties and a nice print out out of the box.

I have written about them in my blog: Improve your code with namedtuples with a couple of examples.

Since they are backwards compatible with regular tuples, they can be used as a drop-in replacement to improve existing code bases one tuple at a time. All the old functions that expect tuples will work fine with regular tuples refactored into named tuples and new things can be made to take advantage of named tuple’s features.

How to use?

from collections import namedtuple
 
# Create a named tuple blueprint
# First argument is its name and second argument is a list of attributes
Point = namedtuple('Point', ['x', 'y', 'z'])
 
# Initialize a named tuple
origin = Point(x=0, y=0, z=0)
 
# Access attributes
print(origin.x)  # prints 0
 
# Improved readability when printed
print(origin)  # prints Point(x=0, y=0, z=0)