Python namedtuple
A namedtuple is a factory function in Python’s collections module that creates tuple subclasses with named fields. It provides an immutable data structure that allows access to elements through descriptive field names instead of numeric indices, making Python namedtuple structures more readable and self-documenting while maintaining the memory efficiency and performance characteristics of regular tuples.
Syntax
namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
Parameters:
typename: A string specifying the name of the new tuple subclassfield_names: A sequence of strings or a single string with field names separated by whitespace and/or commasrename: IfTrue, invalid field names are automatically replaced with positional namesdefaults: An iterable of default values for the rightmost parametersmodule: Value for the__module__field
Return value:
A new tuple subclass with named fields that can be accessed via dot notation.
Example 1: Python namedtuple Basic Example
This example demonstrates how to create a Python namedtuple, access its elements, and perform basic operations in Python:
from collections import namedtuple# Create a namedtuplePerson = namedtuple('Person', ['name', 'age', 'city'])# Create instancesjohn = Person('John Doe', 30, 'New York')jane = Person(name='Jane Smith', age=25, city='Boston')print(john)print(jane)# Access Operationsprint("Access by field name:", john.name)print("Access by index:", john[0])print("Access using getattr:", getattr(john, 'age'))# Conversion Operationsprint("Convert to dict:", john._asdict())# Additional Operationsprint("Field names:", Person._fields)new_person = john._replace(age=31)print("After replace:", new_person)
This example results in the following output:
Person(name='John Doe', age=30, city='New York')Person(name='Jane Smith', age=25, city='Boston')Access by field name: John DoeAccess by index: John DoeAccess using getattr: 30Convert to dict: OrderedDict([('name', 'John Doe'), ('age', 30), ('city', 'New York')])Field names: ('name', 'age', 'city')After replace: Person(name='John Doe', age=31, city='New York')
Conversion Operations
namedtuple provides several useful methods to convert between different data types and create new instances from existing data. These conversion operations make it easy to work with namedtuples alongside other Python data structures like lists, dictionaries, and iterables. There are three main conversion operations available:
- Using
_make(): Createsnamedtupleinstances from iterables - Using
_asdict(): Converts namedtuples to ordered dictionaries - Using
**operator: Creates namedtuples from dictionaries using unpacking
Let’s examine each conversion operation.
Example 2: Using Named Tuples Python _make() Method
Creates a namedtuple instance from an existing iterable, making it easy to convert lists, tuples, or other sequences into namedtuples:
from collections import namedtuple# Create namedtuple classCoordinate = namedtuple('Coordinate', ['x', 'y', 'z'])# Create from different iterablespoint_list = [10, 20, 30]point_tuple = (5, 15, 25)# Use _make() to create instancescoord1 = Coordinate._make(point_list)coord2 = Coordinate._make(point_tuple)print(coord1)print(coord2)
This example results in the following output:
Coordinate(x=10, y=20, z=30)Coordinate(x=5, y=15, z=25)
Example 3: Python Namedtuple _asdict() Method
Converts a namedtuple instance to an OrderedDict, preserving the field names as keys and their corresponding values:
from collections import namedtuple# Create namedtupleStudent = namedtuple('Student', ['name', 'grade', 'subject'])student = Student('Alice Johnson', 95, 'Mathematics')# Convert to dictionarystudent_dict = student._asdict()print("As dictionary:", student_dict)# Access dictionary valuesprint("Name from dict:", student_dict['name'])print("Grade from dict:", student_dict['grade'])
This example results in the following output:
As dictionary: OrderedDict([('name', 'Alice Johnson'), ('grade', 95), ('subject', 'Mathematics')])Name from dict: Alice JohnsonGrade from dict: 95
Example 4: Namedtuple Using ** (Double Star) Operator
Unpacks a dictionary or namedtuple to create new namedtuple instances using keyword arguments:
from collections import namedtuple# Create namedtuple classProduct = namedtuple('Product', ['name', 'price', 'category'])# Create from dictionary using ** operatorproduct_data = {'name': 'Laptop','price': 999.99,'category': 'Electronics'}laptop = Product(**product_data)print("Created from dict:", laptop)# Create from existing namedtuple using _replace (cleanest way)existing_product = Product('Phone', 599.99, 'Electronics')modified_product = existing_product._replace(price=549.99)print("Modified product:", modified_product)
This example results in the following output:
Created from dict: Product(name='Laptop', price=999.99, category='Electronics')Modified product: Product(name='Phone', price=549.99, category='Electronics')
Frequently Asked Questions
1. What is a namedtuple in Python?
A namedtuple is a factory function in the collections module that creates tuple subclasses with named fields. It combines the immutability and memory efficiency of tuples with the readability of accessing elements by name rather than index.
2. How do you create a namedtuple in Python?
You create a namedtuple by calling namedtuple(typename, field_names) where typename is the class name and field_names is a list of field names. For example: Person = namedtuple('Person', ['name', 'age']).
3. What are the 4 collection data types in Python?
The four main built-in collection data types in Python are: list (ordered and mutable), tuple (ordered and immutable), set (unordered and mutable with unique elements), and dict (ordered key-value pairs, mutable). The collections module provides additional specialized data types like namedtuple, deque, Counter, and defaultdict.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours