Python Named Tuples

In the last lesson, we learned about Python Type Hints. Now let us make tuple data easier to read with named fields.

What Is a Named Tuple in Python?

A named tuple is a subclass of tuple with named fields. We can access elements by index, like a regular tuple, or by name.

We create a named tuple using collections.namedtuple.

from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x)
print(p.y)
print(p[0])
print(p[1])

Output

3
4
3
4

We can access the values by name (p.x) or by index (p[0]). That makes the code clearer.

Why Do We Need Named Tuples in Python?

Regular tuples are fine, but they are not self-documenting. If we have a tuple (3, 4), we do not know what 3 and 4 represent.

With a named tuple, we can write Point(x=3, y=4). That is much clearer.

Named tuples are also immutable, like regular tuples. And they use less memory than classes.

How to Create a Named Tuple in Python

We use namedtuple from the collections module.

from collections import namedtuple
Person = namedtuple("Person", ["name", "age", "city"])
person = Person("Alex", 25, "London")
print(person.name)
print(person.age)
print(person.city)

Output

Alex
25
London

That is clean and readable.

Default Values in Named Tuples

We can set default values using _defaults.

from collections import namedtuple
Person = namedtuple("Person", ["name", "age", "city"])
Person.__new__.__defaults__ = ("Unknown",)
person = Person("Alex", 25)
print(person)

Output

Person(name='Alex', age=25, city='Unknown')

That is useful for optional fields.

A Real-Life Example – Coordinates

from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
def distance(p1, p2):
return ((p2.x - p1.x) ** 2 + (p2.y - p1.y) ** 2) ** 0.5
p1 = Point(0, 0)
p2 = Point(3, 4)
print(distance(p1, p2))

Output

5.0

That is much clearer than using p1[0] and p1[1].

Converting Named Tuples to Dictionaries

We can convert a named tuple to a dictionary using _asdict().

from collections import namedtuple
Person = namedtuple("Person", ["name", "age"])
person = Person("Alex", 25)
print(person._asdict())

Output

{'name': 'Alex', 'age': 25}

That is useful when we need a dictionary.

Common Mistakes with Named Tuples in Python

Mistake 1: Trying to change a value

person = Person("Alex", 25)
person.age = 30

This gives an error. Named tuples are immutable.

Fix: Create a new named tuple with _replace().

person = person._replace(age=30)

Mistake 2: Forgetting to import namedtuple

Person = namedtuple("Person", ["name", "age"])

This gives an error.

Fix:

from collections import namedtuple

Mistake 3: Using a list instead of a list of strings

Person = namedtuple("Person", ["name", "age"])

The field names must be strings. They can also be a single string with spaces.

Person = namedtuple("Person", "name age")

Both work.

Mistake 4: Using reserved keywords as field names

Person = namedtuple("Person", ["class", "age"])

class is a keyword. So this gives an error.

Fix: Use a different name, like class_.

Next, we will build a complete Python To-Do Application and use Python concepts together in a real project.