Python namedtuple
last modified November 17, 2026 Python 3.15
In this article we show how to work with named tuples in Python.
A named tuple is a tuple whose elements can also be accessed by
name. It is created with the collections.namedtuple factory
function or by subclassing typing.NamedTuple. The result is a new
subclass of tuple with named fields, a readable
repr, and a few helper methods.
Named tuples are lightweight, immutable record types. They take no more
memory than regular tuples and make code more readable, because
city.population says more than city[1]. They are
similar to records in other languages such as C# or Java.
Basic example
The following is a simple example with a named tuple.
from collections import namedtuple
City = namedtuple('City', 'name population')
c1 = City('Bratislava', 475000)
c2 = City('Budapest', 1686000)
print(c1)
print(c2)
print(isinstance(c1, tuple))
The example creates a City named tuple type and two instances of
it.
from collections import namedtuple
First, we import the namedtuple factory function from the
collections module.
City = namedtuple('City', 'name population')
We define the named tuple type. The first argument is the name of the new
type. The second argument contains the field names; they can be given as a
string separated by spaces or commas, 'name population', or as a
sequence of strings, ['name', 'population'].
c1 = City('Bratislava', 475000)
c2 = City('Budapest', 1686000)
Here we create two named tuple objects. Each of them is also a regular tuple.
$ python basic.py City(name='Bratislava', population=475000) City(name='Budapest', population=1686000) True
Accessing fields
The fields of a named tuple can be accessed with indexes and with their names. All tuple operations work as well.
from collections import namedtuple
City = namedtuple('City', ['name', 'population'])
c1 = City('Bratislava', 475000)
c2 = City(name='Budapest', population=1686000)
print(c1[0])
print(c1[1])
print(c2.name)
print(c2.population)
print(c2[-1])
print(len(c2))
print(c2.index(1686000))
We create the second city with keyword arguments. Then we access the fields
by index and by name, use a negative index, get the length, and find the
index of a value with the index method.
$ python accessing.py Bratislava 475000 Budapest 1686000 1686000 2 1
Unpacking
Unpacking stores the elements of an iterable in variables or passes them as function arguments. Named tuples unpack like regular tuples.
from collections import namedtuple
City = namedtuple('City', 'name population')
c1 = City('Bratislava', 475000)
c2 = City('Budapest', 1686000)
name, population = c1
print(f'{name}: {population}')
print(*c2, sep=': ')
d = {'name': 'Prague', 'population': 1397000}
c3 = City(**d)
print(c3)
We unpack the first city into two variables. The second city is unpacked with
the * operator into the arguments of the print
function, which joins them with the given separator. Finally, the
** operator unpacks a dictionary into keyword arguments of the
City constructor.
$ python unpacking.py Bratislava: 475000 Budapest: 1686000 City(name='Prague', population=1397000)
Immutability
Like tuples, named tuples are immutable; a field cannot be changed after
the object is created. The _replace method returns a new object
with some fields replaced. Since Python 3.13, the generic
copy.replace function does the same for named tuples, dataclasses,
and other types that support it.
import copy
from collections import namedtuple
City = namedtuple('City', 'name population')
c = City('Bratislava', 475000)
try:
c.population = 480000
except AttributeError as e:
print(e)
c2 = c._replace(population=480000)
c3 = copy.replace(c, name='Pressburg')
print(c)
print(c2)
print(c3)
The assignment to the population field fails with an
AttributeError. The _replace and
copy.replace calls create modified copies; the original object
stays unchanged.
$ python immutable.py can't set attribute City(name='Bratislava', population=475000) City(name='Bratislava', population=480000) City(name='Pressburg', population=475000)
Comparing and hashing
Named tuples compare like regular tuples, element by element. Because they are immutable, they are hashable and can be used as dictionary keys or set members, provided their fields are hashable too.
from collections import namedtuple
Point = namedtuple('Point', 'x y')
p1 = Point(1, 2)
p2 = Point(1, 2)
print(p1 == p2)
print(p1 == (1, 2))
print(p1 < Point(1, 3))
labels = {p1: 'start', Point(5, 6): 'end'}
print(labels[p2])
Two points with equal fields are equal, and a point is even equal to a plain
tuple with the same values; the field names are not compared. The ordering
operators compare the fields in order. The p2 point finds the
value stored under the equal p1 key.
$ python hashable.py True True True start
Subclassing
Since a named tuple type is a regular class, we can subclass it and add properties and methods.
from collections import namedtuple
from math import hypot
class Point(namedtuple('Point', 'x y')):
__slots__ = ()
@property
def distance(self):
return hypot(self.x, self.y)
def __str__(self):
return f'Point: x={self.x} y={self.y} distance={self.distance:.3f}'
p = Point(3, 5)
print(p.distance)
print(p)
print(repr(p))
We add the distance property and a custom __str__
method to the Point type. Setting __slots__ to an
empty tuple prevents the creation of a per-instance dictionary, which keeps
the objects as small as plain tuples.
$ python subclassing.py 5.830951894845301 Point: x=3 y=5 distance=5.831 Point(x=3, y=5)
typing.NamedTuple
The typing.NamedTuple class creates named tuples with a class
syntax. The fields are declared with type annotations; default values and
methods are written as in a regular class.
from typing import NamedTuple
class City(NamedTuple):
name: str
population: int
country: str = 'Slovakia'
def describe(self):
return f'{self.name} ({self.country}) has {self.population:,} people'
c1 = City('Bratislava', 475000)
c2 = City('Budapest', 1686000, 'Hungary')
print(c1)
print(c2.describe())
print(City.__annotations__)
The City class has three fields; the country field
has a default value. The type hints are not enforced at runtime, but they are
used by type checkers and IDEs. This is the preferred way of defining named
tuples in modern code.
$ python typed_namedtuple.py
City(name='Bratislava', population=475000, country='Slovakia')
Budapest (Hungary) has 1,686,000 people
{'name': <class 'str'>, 'population': <class 'int'>, 'country': <class 'str'>}
Default values
The defaults parameter of namedtuple provides
default values. The defaults are applied to the rightmost fields.
from collections import namedtuple
Point3D = namedtuple('Point3D', 'x y z', defaults=[0, 0])
print(Point3D(1))
print(Point3D(1, 2))
print(Point3D(1, 2, 3))
print(Point3D._field_defaults)
Two default values are given for three fields, so y and
z default to zero and x is required. The
_field_defaults attribute maps field names to their defaults.
$ python defaults.py
Point3D(x=1, y=0, z=0)
Point3D(x=1, y=2, z=0)
Point3D(x=1, y=2, z=3)
{'y': 0, 'z': 0}
Invalid field names
Field names must be valid identifiers, must not be keywords, must not start
with an underscore, and must be unique. With rename=True,
invalid names are replaced with positional names.
from collections import namedtuple
try:
Row = namedtuple('Row', ['id', 'class', 'name', 'name'])
except ValueError as e:
print(e)
Row = namedtuple('Row', ['id', 'class', 'name', 'name'], rename=True)
print(Row._fields)
print(Row(1, 'A', 'Paul', 'Peter'))
The class field is a keyword and the name field is
duplicated. Without the rename option a ValueError is
raised; with it, the invalid fields are renamed to _1 and
_3 after their positions. This is useful when field names come
from external data, such as a CSV header.
$ python rename.py
Type names and field names cannot be a keyword: 'class'
('id', '_1', 'name', '_3')
Row(id=1, _1='A', name='Paul', _3='Peter')
Helper methods and attributes
Named tuples provide several helpers. Their names start with an underscore to avoid clashes with field names.
from typing import NamedTuple
class Point(NamedTuple):
x: int = 1
y: int = 1
p = Point(5, 7)
print(p._fields)
print(p._field_defaults)
print(p._asdict())
print(p._replace(y=0))
print(Point._make([3, 4]))
The _fields attribute is a tuple of field names and
_field_defaults maps field names to default values. The
_asdict method returns a regular dictionary (an
OrderedDict before Python 3.8), _replace returns a
modified copy, and the _make class method creates a new instance
from an iterable.
$ python helpers.py
('x', 'y')
{'x': 1, 'y': 1}
{'x': 5, 'y': 7}
Point(x=5, y=0)
Point(x=3, y=4)
Serializing to JSON
The _asdict method makes it easy to serialize named tuples to
JSON objects.
import json
from typing import NamedTuple
class City(NamedTuple):
name: str
population: int
cities = [
City('Bratislava', 475000),
City('Budapest', 1686000),
City('Prague', 1397000),
City('Warsaw', 1863000),
]
print(json.dumps(cities[0]._asdict()))
print(json.dumps(cities[0]))
data = json.dumps([city._asdict() for city in cities], indent=2)
print(data)
loaded = [City(**d) for d in json.loads(data)]
print(loaded[-1])
Since a named tuple is a tuple, the json.dumps function
serializes it as a JSON array and the field names are lost. To get JSON
objects, we convert the named tuples with _asdict first. When
loading the data back, the dictionaries are unpacked into the
City constructor.
$ python json_output.py
{"name": "Bratislava", "population": 475000}
["Bratislava", 475000]
[
{
"name": "Bratislava",
"population": 475000
},
{
"name": "Budapest",
"population": 1686000
},
{
"name": "Prague",
"population": 1397000
},
{
"name": "Warsaw",
"population": 1863000
}
]
City(name='Warsaw', population=1863000)
Sorting
In the following example, we sort a list of named tuples by their fields.
from operator import attrgetter
from typing import NamedTuple
class City(NamedTuple):
id: int
name: str
population: int
cities = [
City(1, 'Bratislava', 475000),
City(2, 'Budapest', 1686000),
City(3, 'Prague', 1397000),
City(4, 'Warsaw', 1863000),
City(5, 'Los Angeles', 3820000),
City(6, 'Edinburgh', 512000),
City(7, 'Berlin', 3897000),
]
for city in sorted(cities, key=attrgetter('name')):
print(city)
print('-' * 40)
for city in sorted(cities, key=attrgetter('population'), reverse=True)[:3]:
print(f'{city.name:12} {city.population:>10,}')
The attrgetter function from the operator module
creates a key function that returns the given field. We sort the cities by
name, then we print the three largest cities by population.
$ python sorting.py City(id=7, name='Berlin', population=3897000) City(id=1, name='Bratislava', population=475000) City(id=2, name='Budapest', population=1686000) City(id=6, name='Edinburgh', population=512000) City(id=5, name='Los Angeles', population=3820000) City(id=3, name='Prague', population=1397000) City(id=4, name='Warsaw', population=1863000) ---------------------------------------- Berlin 3,897,000 Los Angeles 3,820,000 Warsaw 1,863,000
Reading CSV data
Named tuples are a good fit for rows of CSV files. We have the following file.
name,population Bratislava,475000 Budapest,1686000 Prague,1397000 Warsaw,1863000 Los Angeles,3820000 New York,8260000 Edinburgh,512000 Berlin,3897000
The first line of the file is a header with the column names.
import csv
from collections import namedtuple
with open('cities.csv', newline='') as f:
reader = csv.reader(f)
City = namedtuple('City', next(reader))
cities = [City._make(row) for row in reader]
for city in cities[:3]:
print(city)
total = sum(int(city.population) for city in cities)
print(f'Total population: {total:,}')
We create the City type from the header row, so the field names
come from the file. Each remaining row is turned into a named tuple with
_make. The csv module returns all values as
strings, so we convert the population to an integer before summing.
$ python read_csv.py City(name='Bratislava', population='475000') City(name='Budapest', population='1686000') City(name='Prague', population='1397000') Total population: 21,910,000
Reading SQLite data
In the following example, we read rows of an SQLite table into named tuples.
import sqlite3
from typing import NamedTuple
class City(NamedTuple):
id: int
name: str
population: int
def city_factory(cursor, row):
return City._make(row)
rows = [
('Bratislava', 475000), ('Budapest', 1686000), ('Prague', 1397000),
('Warsaw', 1863000), ('Edinburgh', 512000), ('Berlin', 3897000),
]
with sqlite3.connect(':memory:') as con:
con.execute('CREATE TABLE cities(id INTEGER PRIMARY KEY, name TEXT, population INTEGER)')
con.executemany('INSERT INTO cities(name, population) VALUES(?, ?)', rows)
con.row_factory = city_factory
for city in con.execute('SELECT * FROM cities WHERE population > 1000000'):
print(city)
We create a cities table in an in-memory database and fill it
with data. The row_factory attribute of the connection is set to
a function that turns each row into a City named tuple. The
query returns the cities with more than a million inhabitants.
$ python read_sqlite.py City(id=2, name='Budapest', population=1686000) City(id=3, name='Prague', population=1397000) City(id=4, name='Warsaw', population=1863000) City(id=6, name='Berlin', population=3897000)
Source
namedtuple – Python collections documentation
typing.NamedTuple – Python typing documentation
In this article we have worked with named tuples in Python. See also Python collections, Python dataclass, Python tuple built-in function, and Python CSV.
Author
List all Python tutorials.