0
0
PythonHow-ToBeginner · 3 min read

How to Use namedtuple in Python: Syntax and Examples

Use namedtuple from the collections module to create simple classes with named fields. Define a namedtuple by giving it a type name and field names, then create instances with those fields accessible by name.
📐

Syntax

The namedtuple function creates a new subclass of tuple with named fields. You provide a type name and a list of field names as strings.

  • Type name: The name of the new tuple class.
  • Field names: A list or space/comma-separated string of field names.
python
from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])

# Create an instance
p = Point(10, 20)

# Access fields
print(p.x)  # 10
print(p.y)  # 20
Output
10 20
💻

Example

This example shows how to define a namedtuple Car with fields make, model, and year. It creates an instance and prints each field by name.

python
from collections import namedtuple

Car = namedtuple('Car', 'make model year')
my_car = Car(make='Toyota', model='Corolla', year=2020)

print(f"Make: {my_car.make}")
print(f"Model: {my_car.model}")
print(f"Year: {my_car.year}")
Output
Make: Toyota Model: Corolla Year: 2020
⚠️

Common Pitfalls

Common mistakes include:

  • Using invalid field names (like keywords or starting with numbers).
  • Trying to modify fields after creation (namedtuples are immutable).
  • Confusing the namedtuple type with an instance.

Always use valid Python identifiers for field names and remember namedtuples behave like tuples, so you cannot change fields once set.

python
from collections import namedtuple

# Wrong: field name '1st' starts with a number
# Person = namedtuple('Person', ['name', '1st'])  # This will raise an error

# Correct:
Person = namedtuple('Person', ['name', 'first'])
p = Person('Alice', 'Smith')

# Trying to change a field (will raise AttributeError)
try:
    p.name = 'Bob'
except AttributeError as e:
    print(e)
Output
can't set attribute
📊

Quick Reference

FeatureDescription
Create namedtuplenamedtuple('TypeName', ['field1', 'field2'])
Access fieldinstance.field1
ImmutableFields cannot be changed after creation
Supports tuple featuresIndexing, unpacking, iteration
Convert to dictinstance._asdict()

Key Takeaways

Use namedtuple to create simple, readable, immutable data objects with named fields.
Define a namedtuple by specifying a type name and valid field names.
Access fields by name for clarity instead of using tuple indexes.
Namedtuples are immutable; you cannot change fields after creation.
Use _asdict() method to convert namedtuple instances to dictionaries.