Tutorial

Named Tuples Python

6 min read

Named tuples were created to enhance code readability by allowing us to give descriptive names to elements of a tuple while retaining the immutability property. In this article, we will discuss named tuples in Python and demonstrate how to use them with practical examples.

Note

If you need help in understanding tuples, you can read the following article on Python tuples: Tuples in Python.

What are named tuples in Python?

The namedtuple Python function is a member of the collections module.

With the namedtuple function, we can specify names for each element of the tuple we create. This allows us to access elements using dot notation (like a regular class) rather than by numerical index.

This eases the headaches and bugs that result when trying to figure out which index to use to access a particular data item in a tuple.

As a result, namedtuple‘s make our code more readable and self-documenting, providing structure without the need for custom classes.

Define Python named tuple

To begin, we will need to import the Python namedtuple function from the collections module in the Python standard library.

The following code example illustrates how to create a Person named tuple:

from collections import namedtuple

# Define a named tuple class for personal information
Person = namedtuple('Person', ['first_name', 'last_name', 'age', 'email', 'phone_number'])

In this code example, the call to the namedtuple function produces a named tuple class called Person, with the fields first_name, last_name, age, email, and phone_number.

Creating instances of named tuples in Python

As seen in the previous section, creating a named tuple class was easy!

However, how do we use the definition so created? In other words, how do we create instances from our named tuple class?

The next code example will illustrate how this can be accomplished:

from collections import namedtuple

def create_person(first_name, last_name, age, email, phone_number):
    # Define a named tuple class for personal information
    Person = namedtuple('Person', ['first_name', 'last_name', 'age', 'email', 'phone_number'])

    # create the person instance
    person_named_tuple = Person(first_name, last_name, age, email, phone_number)

    return person_named_tuple

person1 = create_person('John', 'Doe', 30, 'john.doe@email.com', '123-456-7890')

We defined a function, create_person, which helps in creating an instance of the named tuple class.

To create an instance, we pass the person’s details to the Person constructor. The constructor returns a Person named tuple instance.

The last line of code shows how to make use of it.

Note

Learn about creating class instances (or, objects) in Python by reading this tutorial on Class, Objects in Python.

Accessing named fields in Python

So, how do we access the elements in our named tuple instance?

Simple: we use the dot notation used for referencing attributes in a class instance.

For example, we can easily access the age and email fields from the instance, person1, we created in the previous section.

print(f"Age: {person1.age}")
print(f"Email: {person1.email}")

Output:
output of named tuple age and email fields

We can still make use of the index notation (see the next example):

print(f"Age: {person1[2]}")
print(f"Email: {person1[3]}")

However, the previous dot notation was more readable than the index notation. With the index notation, we had to do some looking and position counting in order to get the correct index for the values we were looking for.

On the other hand, the dot notation not only improved the readability of the code but also reduced the risk of going out of bounds or accessing the wrong data field.

Extended example: Create a list of named tuples in Python

Let’s extend our previous examples and put the concept of named tuples into practice. In the next example, we want to create a list of personal information for some individuals.

The code below shows one possible way we can get the information for the individuals, and create the Person instances we need.

# Define a list of information about people
# Each info is a regular tuple
people_info = [
    ('John', 'Doe', 30, 'john.doe@email.com', '123-456-7890'),
    ('Jane', 'Smith', 25, 'jane.smith@email.com', '987-654-3210'),
    ('Bob', 'Johnson', 45, 'bob.johnson@email.com', '555-123-4567'),
    ('Alice', 'Williams', 28, 'alice.williams@email.com', '777-888-9999')
]

# Create a list of people
people = [create_person(*person_info) for person_info in people_info]

In this example, we first created a list of tuples containing the information of individuals we needed to manage.

Then, we made use of our previously defined create_person function inside a list comprehension (and tuple unpacking) to convert our list of regular tuples into a list of Person named tuple instances.

Displaying personal information

In order to display information for each person, we define a function as_str to convert a `Person` named tuple to a string representation:

def as_str(person):
    val = ""
    val += f"Name: {person.first_name} {person.last_name}\n"
    val += f"Age: {person.age}\n"
    val += f"Email: {person.email}\n"
    val += f"Phone Number: {person.phone_number}\n"

    return val

for person in people:
    print(as_str(person))

We then iterate through the list of people, calling this function within the print to return a string representation of each person and print it out to the console.

The output is as follows:

output named tuples as string

Note

Learn more about f-strings in Python from the article Strings in Python.

Below, we have the complete code to create a list of Person named tuples and display all the information in a readable form.


from collections import namedtuple

def create_person(first_name, last_name, age, email, phone_number):
    '''Create and return a named tuple Person instance'''
    # Define a named tuple class for personal information
    Person = namedtuple('Person', ['first_name', 'last_name', 'age', 'email', 'phone_number'])

    # create the person instance
    person_named_tuple = Person(first_name, last_name, age, email, phone_number)

    return person_named_tuple

def as_str(person):
    '''Create an return a string representation for the person'''
    val = ""
    val += f"Name: {person.first_name} {person.last_name}\n"
    val += f"Age: {person.age}\n"
    val += f"Email: {person.email}\n"
    val += f"Phone Number: {person.phone_number}\n"

    return val

# Define a list of information about people
# Each info is a regular tuple
people_info = [
    ('John', 'Doe', 30, 'john.doe@email.com', '123-456-7890'),
    ('Jane', 'Smith', 25, 'jane.smith@email.com', '987-654-3210'),
    ('Bob', 'Johnson', 45, 'bob.johnson@email.com', '555-123-4567'),
    ('Alice', 'Williams', 28, 'alice.williams@email.com', '777-888-9999')
]

# Create a list of people
people = [create_person(*person_info) for person_info in people_info]

# display all the information about all the persons in the people list
for person in people:
    print(as_str(person))

Named tuples are a valuable tool for managing structured data in Python. They enhance code clarity and maintainability, making it easier to work with data without the need for custom classes or dictionaries.

Whether you’re handling personal information, configuration settings, or any structured data, named tuples can simplify your code and improve its readability.

You might also like, to learn Python with the help of Python tuition.