Some examples of namedtuples in Python Python 10.10.2016

The collections.namedtuple function is a factory that produces subclasses of tuple enhanced with field names and a class name.

Instances of a class that you build with namedtuple take exactly the same amount of memory as tuples because the field names are stored in the class. They use less memory than a regular object because they do store attributes in a per-instance __dict__.

Following example defines named tuple to hold information about a city

>>> from collections import namedtuple
>>> City = namedtuple('City', 'name country population coordinates')
>>> vn = City('Vinnytsia', 'UA', 369.860, (49.233333, 28.483333))
>>> vn
City(name='Vinnytsia', country='UA', population=369.860, coordinates=(49.233333, 28.483333))
>>> vn.population
369.860
>>> vn.coordinates
(49.233333, 28.483333)
>>> vn[2]
369.860

Or let's define a point

>>> Point = namedtuple('Point', ['x', 'y'])
>>> pt1 = Point(2, 7)
>>> pt.x
2

Two parameters are required to create a named tuple: a class name and a list of field names, which can be given as an iterable of strings or as a single space-delimited string.

Data must be passed as positional arguments to the constructor (in contrast, the tuple constructor takes a single iterable). You can't set attributes of a namedtuple, just like you can't change members of a tuple. You need to set attributes when you instantiate your namedtuple.

You can access the fields by name or position.