How to use namedtuples in python

The namedtuple() is a factory function for creating tuples with named fields. A normal tuple is built into python so it doesn’t need to be imported as indicated in the code snippet below:

>>> chars = ('a', 'z', 'e', 'y', 'o', 'I')

You can access the ‘z’ element by accessing its respective index as shown below:

>>> chars[1]

The details for creating a namedtuple is indicated below:

collections.namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)

The above returns a tuple subclass named typename. The subclass is used to create objects similar to tuples. The properties of a tuple will be inherited in the subclass such as the ability to index, slice, and iterate. However, in addition to accessing elements by their index, namedtuples can also access elements by their field_names. Like traditional tuples namedtuples are also immutable.

How to create a namedtuple

In order to create a namedtuple you must import the namedtuple class as indicated in the following code snippet:

>>> from collections import namedtuple

The first parameter or typename indicates what type you want followed by strings containing the field_name. Instances of the subclass contains a docstring which holds the typename and field_names, and a __repr__() method which displays the tuple contents in a name=value format. Below is an example of a namedtuple in action:

>>> from collections import namedtuple
>>> basketball = namedtuple('Team', 'name arena championships')
>>> team_1 = basketball('Golden State Warriors', 'Oracle', 6)
>>> team_1
Team(name='Golden State Warriors', arena='Oracle', championships=6)
>>> team_2 = basketball('LA Lakers', 'Staples Center', 16)
>>> team_2
Team(name='LA Lakers', arena='Staples Center', championships=16)
# accessing elements by index
>>> team_1[0] # accessing elements by index
'Golden State Warriors'
>>> team_2[1]
'Staples Center'
# accessing elements via fields 
'Golden State Warriors'
>>> average = (team_1.championships + team_2.championships) / 2
>>> average
>>> name, arena, championships = team_1
>>> name
'Golden State Warriors'
>>> arena
>>> championships
============================================================================ Want to learn how to use Python's most popular IDE Pycharm? In the free pdf guide "Getting the Hang of PyCharm" you'll learn all of the amazing features in PyCharm along with how to get started with data science. Subscribe to the Purcell Consult newsletter and get started A.S.A.P.