Python Tuples · Lesson 51 of 149

Python Named Tuples

What you will learn

  • Why plain tuples can be hard to read, and how namedtuple fixes it
  • How to create one and read fields by name or by index
  • That a named tuple is still a tuple: unpacking, comparing, dictionary keys
  • _replace, _asdict, _fields and default values
  • The class form, typing.NamedTuple, with types and methods
  • When to choose a named tuple, a dictionary or a dataclass

1. The problem with plain tuples

A tuple is a good way to keep a small record together, but you must remember what each position means:

person = ("Rina", 25, "Dhaka")
print(person[1])
25

What is [1]? After a few weeks, nobody remembers. A named tuple gives each position a name, and still costs no more than a tuple.

2. Creating a named tuple type

namedtuple lives in the collections module. You give it the name of the new type and the field names:

from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p)
print(p.x, p.y)
print(p[0], p[1], len(p))
Point(x=3, y=4)
3 4
3 4 2
  • namedtuple("Point", ["x", "y"]) creates a new type called Point. Store it in a name, usually the same one.
  • Point(3, 4) makes one record. The nice printed form shows the field names.
  • Read a field by name (p.x) or by position (p[0]).

The field names may also be written as one string with spaces or commas between them:

Person = namedtuple("Person", "name age city")
r = Person("Rina", 25, "Dhaka")
print(r, r.name, r.city)
Person(name='Rina', age=25, city='Dhaka') Rina Dhaka

You can give the values by name, in any order, or from a list with _make:

print(Point(y=1, x=2))
print(Point._make([7, 8]))
print(Point(*[5, 6]))
Point(x=2, y=1)
Point(x=7, y=8)
Point(x=5, y=6)

Too few or too many values is an error:

Point(1)
TypeError: Point.__new__() missing 1 required positional argument: 'y'
Quick check: how do you read the `age` of `r` in the example above?

r.age (or r[1]). The name is much clearer.

3. It is still a tuple

A named tuple is a tuple, so everything from lessons 8.1 to 8.3 works:

x, y = p
print(x, y, tuple(p), sum(p), max(p))
print(isinstance(p, tuple))
print(p == (3, 4), p < Point(3, 5))
print(sorted([Point(2, 1), Point(1, 5)]))
3 4 (3, 4) 7 4
True
True True
[Point(x=1, y=5), Point(x=2, y=1)]
  • It can be unpacked (lesson 8.2) and looped over.
  • It equals the plain tuple with the same values.
  • It sorts and compares item by item, like a tuple.
  • It is hashable, so it can be a dictionary key (chapter 9):
d = {Point(0, 0): "origin"}
print(d[Point(0, 0)], d[(0, 0)])
origin origin

Immutable

Like any tuple, you cannot change a field:

p.x = 10
AttributeError: can't set attribute

(The exact message differs between Python versions.)

4. Helper methods and attributes

The helper names start with an underscore, to keep them away from your own field names. They are still public and meant to be used:

Name What it does Example result
p._replace(x=99) a new named tuple with some fields changed Point(x=99, y=4)
p._asdict() the fields as a dictionary {'x': 3, 'y': 4}
p._fields the field names ('x', 'y')
Point._make(items) build from a collection Point(x=7, y=8)
print(p._replace(x=99))
print(p)
print(p._asdict())
print(p._fields)
Point(x=99, y=4)
Point(x=3, y=4)
{'x': 3, 'y': 4}
('x', 'y')

_replace leaves the original unchanged and returns a new one, which is how you "change" an immutable record. _asdict() is handy for converting to JSON (lesson 15.7).

5. Default values

Give defaults for the last fields. They are used when you leave those values out:

Item = namedtuple("Item", ["name", "price", "qty"], defaults=[1])
print(Item("pen", 2.5))
print(Item("pen", 2.5, 4))
Item(name='pen', price=2.5, qty=1)
Item(name='pen', price=2.5, qty=4)

defaults=[1] fills in the last field (qty).

6. Field name rules

Field names must be valid Python names, with no repeats, and none may start with an underscore:

Mistake Error
["x", "x"] ValueError: Encountered duplicate field name: 'x'
["1x"] ValueError: Type names and field names must be valid identifiers: '1x'
["_x"] ValueError: Field names cannot start with an underscore: '_x'

With rename=True, invalid names (and keywords such as class) are replaced by _0, _1 and so on instead of raising an error. This is mostly useful when the names come from outside, such as a file's header row.

7. The class form: typing.NamedTuple

typing.NamedTuple lets you write a named tuple as a class, with types, defaults and methods (classes are chapter 13):

from typing import NamedTuple

class Employee(NamedTuple):
    name: str
    dept: str = "none"
    salary: float = 0.0

    def raise_pct(self, pct):
        return self._replace(salary=self.salary * (1 + pct / 100))

    @property
    def summary(self):
        return f"{self.name} ({self.dept})"

e = Employee("Sam", "IT", 1000.0)
print(e)
print(e.summary)
print(e.raise_pct(10))
print(Employee("Lee"))
Employee(name='Sam', dept='IT', salary=1000.0)
Sam (IT)
Employee(name='Sam', dept='IT', salary=1100.0)
Employee(name='Lee', dept='none', salary=0.0)
  • Each line name: type defines a field; = value gives a default.
  • Methods and properties can be added.
  • It is still an immutable tuple underneath.

The types (str, float) are hints for readers and tools; Python does not check them when the program runs (type hints are lesson 19.1).

8. Named tuple, dictionary or dataclass?

named tuple dictionary dataclass
access p.x or p[0] p["x"] p.x
can change no yes yes (unless frozen=True)
unpack like a tuple yes no no
hashable yes no only if frozen=True
methods and logic few none yes
size same as a tuple larger an object

In a quick test, Point(1, 2) and (1, 2) each used 56 bytes, and a dictionary with the same two fields used 184. Rule of thumb:

  • a small, fixed record that you pass around or use as a key: named tuple;
  • a record with changing values or real behaviour: dataclass (lesson 13.11);
  • a flexible bag of fields decided at run time: dictionary.

Worked example: a team

Keep a team's members as named tuples, find the oldest, sort by age, and give one a new city.

from collections import namedtuple

Person = namedtuple("Person", "name age city")
team = [
    Person("Rina", 25, "Dhaka"),
    Person("Sam", 22, "Khulna"),
    Person("Lee", 31, "Sylhet"),
]

oldest = max(team, key=lambda m: m.age)
print(oldest.name, oldest.age)

by_age = sorted(team, key=lambda m: m.age)
print([m.name for m in by_age])

moved = team[1]._replace(city="Dhaka")
print(moved)
print(team[1])
Lee 31
['Sam', 'Rina', 'Lee']
Person(name='Sam', age=22, city='Dhaka')
Person(name='Sam', age=22, city='Khulna')
Step What it shows
max(team, key=lambda m: m.age) fields read by name in a key function
sorted(...) records sorted by one field
_replace(city=...) a new record; the original keeps Khulna

The names, ages and cities are made up.

Common mistakes

  • Trying to assign to a field (p.x = 10). Use _replace to make a new record.
  • Forgetting that Point is the new type's name, not the field list: write Point(3, 4).
  • Field names starting with an underscore, repeated, or not valid names.
  • Adding two named tuples and expecting another named tuple: Vec(1, 2) + Vec(3, 4) gives a plain tuple (1, 2, 3, 4).
  • Expecting type hints in NamedTuple to be checked. They are not.

Key takeaways

  • namedtuple("Point", "x y") makes a tuple type whose fields have names; read them as p.x or p[0].
  • It is a real tuple: unpack it, compare it, sort it, use it as a dictionary key.
  • _replace makes a changed copy, _asdict converts to a dictionary, _fields lists the names, defaults= sets defaults for the last fields.
  • typing.NamedTuple is the class form, with types, defaults and methods.
  • Choose a named tuple for small fixed records, a dataclass for changing records with behaviour, a dictionary for flexible fields.

Practice

1. Define a named tuple type Book with fields title and pages, and make one.

Show answer
from collections import namedtuple

Book = namedtuple("Book", "title pages")
b = Book("Python", 300)

2. How do you read the pages of b, in two ways?

Show answer

b.pages and b[1].

3. What does b._replace(pages=350) do to b?

Show answer

Nothing: b is unchanged. It returns a new Book with pages set to 350.

4. Why does b.pages = 10 fail?

Show answer

A named tuple is immutable, like every tuple, so its fields cannot be assigned. Python raises an AttributeError.

5. Give Book a default pages of 100.

Show answer

Book = namedtuple("Book", "title pages", defaults=[100]).

6. Which would you use for a record whose values change often and that needs methods?

Show answer

A dataclass (lesson 13.11), because a named tuple is immutable.