Named Tuples in Python With Example

Named tuples subclass standard tuple types and add a layer to assign property names to the positional elements. Using named tuples we can assign name to elements in tuple and these elements can be accessed using dot notation just like accessing property from object instance.

Why to Use Named Tuples?

You should use named tuples instead of tuples to make your code more object oriented and pythonic like so that it is easy to read and understand.

Named Tuples Example

Named tuples are located in the standard library module called collections. It can be imported using from collections import namedtuple

Following examples illustrates the concept of namedtuple:

Using Positional Arguments

# importing named tuple
from collections import namedtuple

# using named tuple
Person = namedtuple('Person','name age country')

# creating named tuple
p1 = Person("Jeffery Way", 38, "United States")

# accessing elements using property name
print("Age:", p1.age)


Name: Jeffery Way
Age: 38
Country: United States

Using Keyword Arguments

from collections import namedtuple

Point3D = namedtuple('Point3D', 'x y z')

# You can use keyword arguments as well
pt = Point3D(x= 10, y = 30, z = 20)

print("Point is: ", pt)


Point is:  Point3D(x=10, y=30, z=20)


Named tuple is not a new data structure type but it is a function that generates new classes. So it is a class factory. New classes which are generated using namedtuple inherit from standard tuple class but they also provide named properties to access elements of the tuple.

Remember instance of new class is still a tuple and all operations that can be done with tuple are valid. See example below:

from collections import namedtuple

Point3D = namedtuple('Point3D', 'x y z')

pt = Point3D(10, 30, 20)

print("Maximum value in point is: ", max(pt))
print("Minimum value in point is: ", min(pt))
print("Point is: ", pt)
print("And fields in point are: ", pt._fields)


Maximum value in point is:  30
Minimum value in point is:  10
Point is:  Point3D(x=10, y=30, z=20)
And fields in point are:  ('x', 'y', 'z')

When we use named tuples, we are essentially creating a new class. namedtuple needs a few things to generate this class:

  1. The class name we want to use. In the above example, 'Person' is class name.
  2. A sequence of field strings we want to assign, in the order of the elements in the tuple field. In the above example, 'name age country' are field names.

    Name can be any valid identifier except they can not start with underscore ( _ ).

    If you want to use underscore ( _ ) pass keyword arguments like: rename = True in function namedtuple().

The return value of the namedtuple will be a class. We need to assign this class to a variable name so we can use it to construct instances. In general, we use the same name as the name of the class that was generated. So, Person is used as a variable name for class.