Named Tuples in Python

| Wednesday, January 22, 2025

Named Tuples in Python

Written by John Strickler


When you need to represent a list of identical objects with different values, you start with a list of tuples. It’s an efficient way to hold a collection of related data. Tuples are like structures or records in other languages, but indexed with integers, like lists. You can build a list named people, where each element is a tuple of three elements: first name, last name, and zip code. To get the zip code for the first element, you can use people[0][2].

The problem comes when you want to read in a file where each line has 17 fields. It gets really hard to remember which index is for which field. At this point, many programmers create a class with read-only properties for this purpose, so they can say class.field (e.g., people[0].first_name, people[0].last_name, etc.). Such a class has no methods; it only exists to store the data.

It’s overkill to use a class for this purpose. Python provides an elegant solution – named tuples. A named tuple is exactly like a normal tuple, except that the fields can also be accessed by .fieldname. Named tuples are still immutable, you can still index elements with integers, and you can iterate over the elements. With a named tuple, you can say record.first_name, record.last_name, as with a class, but without the extra code of a class. There’s no need to write all the property definitions.

Creating a Named Tuple

To create a named tuple, import the namedtuple class from the collections module. The constructor takes the name of the named tuple (which is what type() will report), and a string containing the fields names, separated by whitespace. It returns a new namedtuple class for the specified fields. To use it, call the new class with all the values (in order) as parameters. Remember, the tuple is still immutable. You can’t change it or add fields later. All fields must be supplied.

Remember, when you need a structure with field names, use a named tuple.

Example

>>> from collections import namedtuple

>>> Person = namedtuple('Person', 'first_name last_name zip_code')

>>> p1 = Person('Joe', 'Schmoe', '93002')

>>> p1.first_name

'Joe'

>>> p1[0]

'Joe'

>>> p1.zip_code

'92002'

>>> len(p1)

3

>>> type(p1)

<class '__main__.Person'>

>>> 


Written by John Strickler

John is a long-time trainer and has taught all over the US. He is a programmer, trainer, and consultant for Python, SQL, Django, and Flask.

Looking for Python training for software development or data science?

Find the Perfect Python Course
Introduction to Python Programming (Practical Programming for Beginners)
Data Science Using Python Deep Dive
Best Agile Certifications

Best Agile Certifications

If you want to advance in your career operating in an Agile framework, then obtaining an Agile certification is the right step forward. Learn which Agile certifications are right for you in our blog post.

News