Python
named tuples
programming
data structures
Python tutorial

What are named tuples in Python?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Named tuples in Python are an extension of regular tuples, providing a way to define simple classes that hold data without having to write the boilerplate code usually associated with classes. Named tuples are part of Python's collections module and are commonly used when you want to create data objects with named fields, improving code readability and maintainability.

What Are Named Tuples?

A named tuple is like a regular tuple, but the fields can also be accessed using field names instead of just index positions. This makes your code more self-documenting and less error-prone, as you don't have to remember which index corresponds to which piece of data.

Here's a quick example to illustrate a basic named tuple:

python
1from collections import namedtuple
2
3# Define a named tuple type
4Point = namedtuple('Point', ['x', 'y'])
5
6# Create an instance of the named tuple
7p = Point(2, 3)
8
9# Access values using field names
10print(p.x)  # 2
11print(p.y)  # 3
12
13# Access values using index
14print(p[0])  # 2
15print(p[1])  # 3

Key Characteristics of Named Tuples

  1. Immutability: Like regular tuples, named tuples are immutable. Once you create an instance, its values cannot be modified.
  2. Readable Field Access: You can access data elements by descriptive names, making the code more readable.
  3. Lightweight: Named tuples are as memory efficient as regular tuples because they do not have per-instance dictionaries.
  4. Iterable: Named tuples can be unpacked or iterated over just like regular tuples.

How to Create Named Tuples

Named tuples are defined using the namedtuple() factory function from the collections module. This function requires two arguments: the name of the new class and the field names. Field names can be given as a string of space-separated names or a list.

python
1# Using space-separated strings
2Person = namedtuple('Person', 'name age job')
3
4# Using a list
5Person = namedtuple('Person', ['name', 'age', 'job'])

Advanced Features

Default Values

Named tuples do not support default values out of the box, but you can create a subclass of namedtuple to add this feature:

python
1from collections import namedtuple
2
3# Create a subclass of Point with default values
4class Point(namedtuple('Point', ['x', 'y'])):
5    __slots__ = ()
6    def __new__(cls, x=0, y=0):
7        return super(Point, cls).__new__(cls, x, y)
8
9p = Point()
10print(p)  # Point(x=0, y=0)
11
12p_with_x_set = Point(x=5)
13print(p_with_x_set)  # Point(x=5, y=0)

Methods and Docstrings

You can also add methods and docstrings to named tuples by subclassing:

python
1class Point(namedtuple('Point', ['x', 'y'])):
2    """Represents a point in 2D space."""
3    __slots__ = ()
4    
5    def __str__(self):
6        return f"Point({self.x}, {self.y})"
7    
8    def distance_to_origin(self):
9        return (self.x ** 2 + self.y ** 2) ** 0.5
10
11p = Point(3, 4)
12print(p.distance_to_origin())  # 5.0

Performance Considerations

Compared to regular classes, named tuples provide a significant performance advantage due to their lightweight nature. However, if you need an object with mutable fields or significant methods and logic, you should consider using classes.

Named Tuples vs Data Classes

In Python 3.7, data classes were introduced with the dataclass decorator, providing similar functionality with additional features such as default values and type checking. While data classes are more flexible, named tuples remain popular for quick-and-clean use cases where immutability is desired without the overhead of a full class definition.

Summary Table

Here is a table summarizing key points about named tuples:

FeatureNamed Tuples Benefits
ImmutabilityValues cannot be changed after creation.
Field AccessAccess using descriptive names, enhancing readability.
Memory EfficiencyAs efficient as tuples, no per-instance dictionaries.
IterableCan be unpacked or iterated same as regular tuples.
Default ValuesCan be added by subclassing the named tuple. Not built-in.
Extension with MethodsCan add methods by subclassing, similar to classes.
PerformanceFaster than regular classes for attribute access.
Comparison with Data ClassQuick setup like tuples; data classes offer more features.

In conclusion, named tuples offer a simple, efficient way to create objects that are immutable and can be accessed using field names, making them an elegant solution for many scenarios in Python programming.


Course illustration
Course illustration

All Rights Reserved.