named tuple
In Python, a named tuple is a variation of the built-in tuple
data type that allows you to create tuple-like objects whose items have a descriptive name. You can access each item by its name using the dot notation.
Named tuples are part of the collections
module and are especially useful when you want to write more readable and self-documenting code.
Named tuples are immutable, just like regular tuples, which means that once you create a named tuple, you can’t change its values.
Example
Here’s a quick example of how to use named tuples in Python:
>>> from collections import namedtuple
>>> Point = namedtuple("Point", ["x", "y"])
>>> point = Point(11, 22)
>>> point.x
11
>>> point.y
22
In this example, Point
is a named tuple with two fields, .x
and .y
. You can create an instance of Point
by providing values for these fields. Then, you can access those items using the dot notation, which makes the code more readable.
Related Resources
Tutorial
Write Pythonic and Clean Code With namedtuple
In this step-by-step tutorial, you'll learn what Python's namedtuple is and how to use it in your code. You'll also learn about the main differences between named tuples and other data structures, such as dictionaries, data classes, and typed named tuples.
For additional information on related topics, take a look at the following resources:
- Python's collections: A Buffet of Specialized Data Types (Tutorial)
- Lists vs Tuples in Python (Tutorial)
- Python's tuple Data Type: A Deep Dive With Examples (Tutorial)
- Writing Clean, Pythonic Code With namedtuple (Course)
- Write Pythonic and Clean Code With namedtuple (Quiz)
- Lists and Tuples in Python (Course)
- Lists vs Tuples in Python (Quiz)
- Exploring Python's tuple Data Type With Examples (Course)
By Leodanis Pozo Ramos • Updated April 24, 2025