collections.namedtuple

Creates tuples with named fields: you read data with student.points instead of student[2], and the object stays immutable.

Returns
A new class that inherits from tuple.
On this page

Example

#
Python
from collections import namedtuple

Student = namedtuple("Student", ["name", "world", "points"])

emma = Student("Emma", 7, 250)
print(emma)
print(emma.name, emma.points)
print(emma[1], len(emma))

name, world, points = emma
print(f"{name} is in world {world}")
Resultsaved result, you can check it
Student(name='Emma', world=7, points=250)
Emma 250
7 3
Emma is in world 7

Definition and usage

#

The namedtuple() function from the collections module creates a new class of tuples in which every field has a name. Instead of remembering that in the tuple ("Emma", 7, 250) the points are at index 2, you write student.points. The objects are still ordinary tuples, so indexing, unpacking, comparing, and len() all work.

Like any tuple, the object is immutable: assigning to a field raises AttributeError. A new version with a changed field is created by the _replace() method, and _asdict() turns the object into a dictionary. The _fields attribute holds the field names, and _make() creates an object from any sequence, e.g. a row from a CSV file. The underscore in these names does not mean they are private, it just prevents conflicts with the names of your fields.

A more modern notation is a class that inherits from typing.NamedTuple, in which fields are declared with type annotations, similar to @dataclass. When you need an object whose fields can change, choose @dataclass.

Syntax

#
Syntax
from collections import namedtuple

Name = namedtuple("Name", ["field1", "field2"], defaults=None)
obj = Name(value1, value2)
obj.field1
obj._replace(field1=new_value)
obj._asdict()

Parameters

#
  • typename

    str

    The name of the new class, visible in repr() among other places. Usually the same as the variable name.
  • field_names

    list of strings or a string

    The field names, e.g. ["x", "y"] or "x y".
  • defaults

    sequence, optional

    Default values for the last fields.

More examples

#
Immutability, _replace(), and _asdict()
Python
from collections import namedtuple

Student = namedtuple("Student", "name points level", defaults=[1])

jack = Student("Jack", 80)
print(jack)

try:
    jack.points = 120
except AttributeError:
    print("The field cannot be changed")

promoted = jack._replace(points=120, level=2)
print(promoted)
print(promoted._asdict())
print(Student._fields)
Resultsaved result, you can check it
Student(name='Jack', points=80, level=1)
The field cannot be changed
Student(name='Jack', points=120, level=2)
{'name': 'Jack', 'points': 120, 'level': 2}
('name', 'points', 'level')
typing.NamedTuple with type annotations
Python
from typing import NamedTuple

class Point(NamedTuple):
    x: float
    y: float = 0.0

    def distance(self):
        return (self.x ** 2 + self.y ** 2) ** 0.5

p = Point(3, 4)
print(p, p.distance())
print(Point(1.5))
print(sorted([Point(2, 1), Point(1, 5), Point(1, 2)]))
Resultsaved result, you can check it
Point(x=3, y=4) 5.0
Point(x=1.5, y=0.0)
[Point(x=1, y=2), Point(x=1, y=5), Point(x=2, y=1)]

Annotations do not convert types: Point(3, 4) stores integers. Sorting compares the fields one by one, as in ordinary tuples.

_make() and rows from a CSV file
Python
import csv
from collections import namedtuple

lines = ["name,world,points", "Emma,7,250", "Jack,2,80"]
reader = csv.reader(lines)
Row = namedtuple("Row", next(reader))

for row in map(Row._make, reader):
    print(row.name, int(row.points))
Resultsaved result, you can check it
Emma 250
Jack 80

Good practices

#
  • The methods _replace(), _asdict(), and _make() are public despite the underscore. The underscore protects against a conflict with the names of your fields.
  • A namedtuple works well for returning several values from a function: you unpack the result like a tuple or read it by field names.
  • If fields need to change, or the class needs many methods, use @dataclass.

Related entries

#

Spotted a mistake or missing an example? Write to us.