Header Ads Widget

⚡ Premium Tools Hub • EXE Apps + Full Python Source Code
Lite • Pro • Bundle Packs • Instant Download

Python NamedTuple – Complete Guide for Beginners

When working with Python, we often use tuples to store multiple values in a single variable. Traditional tuples are lightweight and fast, but accessing values by index can make code difficult to read and maintain.

Python provides NamedTuple, which allows tuple elements to be accessed using meaningful names instead of numeric indexes.

NamedTuple combines the memory efficiency of tuples with the readability of objects, making it an excellent choice for storing structured data.


What is NamedTuple?

A NamedTuple is a tuple subclass that allows fields to be accessed by name rather than position.

It is available in Python's built-in collections module.

Regular Tuple Example

person = ("John", 25, "Developer")

print(person[0])
print(person[1])

Output:

John
25

While this works, it's not obvious what index 0 or 1 represents.


Using NamedTuple

from collections import namedtuple

Person = namedtuple("Person", ["name", "age", "job"])

person = Person("John", 25, "Developer")

print(person.name)
print(person.age)
print(person.job)

Output:

John
25
Developer

The code is now much easier to understand.


Syntax of NamedTuple

from collections import namedtuple

ClassName = namedtuple(
    typename,
    field_names
)

Parameters:

ParameterDescription
typenameName of the NamedTuple class
field_namesList or string containing field names

Example:

Student = namedtuple(
    "Student",
    ["name", "age", "grade"]
)

Creating a NamedTuple

from collections import namedtuple

Car = namedtuple(
    "Car",
    ["brand", "model", "year"]
)

car1 = Car("Toyota", "Corolla", 2024)

print(car1)

Output:

Car(brand='Toyota', model='Corolla', year=2024)

Accessing NamedTuple Values

Access by Field Name

print(car1.brand)
print(car1.model)
print(car1.year)

Output:

Toyota
Corolla
2024

Access by Index

NamedTuple still behaves like a tuple.

print(car1[0])
print(car1[1])

Output:

Toyota
Corolla

Iterating Through a NamedTuple

for value in car1:
    print(value)

Output:

Toyota
Corolla
2024

NamedTuple is Immutable

Like regular tuples, NamedTuples cannot be modified after creation.

car1.year = 2025

Output:

AttributeError:
can't set attribute

This immutability helps prevent accidental changes.


Using _replace()

To create an updated copy, use _replace().

updated_car = car1._replace(year=2025)

print(updated_car)

Output:

Car(
    brand='Toyota',
    model='Corolla',
    year=2025
)

The original object remains unchanged.


Using _fields

The _fields attribute returns all field names.

print(Car._fields)

Output:

('brand', 'model', 'year')

Converting NamedTuple to Dictionary

Use _asdict().

print(car1._asdict())

Output:

{
    'brand': 'Toyota',
    'model': 'Corolla',
    'year': 2024
}

This is useful when working with JSON or APIs.


Creating NamedTuple from Dictionary

data = {
    "brand": "Tesla",
    "model": "Model Y",
    "year": 2024
}

car = Car(**data)

print(car)

Output:

Car(
    brand='Tesla',
    model='Model Y',
    year=2024
)

NamedTuple with Default Values

Python 3.7+ supports defaults.

from collections import namedtuple

Employee = namedtuple(
    "Employee",
    ["name", "salary"],
    defaults=[0]
)

emp = Employee("David")

print(emp)

Output:

Employee(
    name='David',
    salary=0
)

Real-World Example: Student Records

from collections import namedtuple

Student = namedtuple(
    "Student",
    ["id", "name", "course"]
)

students = [
    Student(1, "Alice", "Python"),
    Student(2, "Bob", "Data Science"),
    Student(3, "Charlie", "AI")
]

for student in students:
    print(
        student.id,
        student.name,
        student.course
    )

Output:

1 Alice Python
2 Bob Data Science
3 Charlie AI

NamedTuple vs Tuple

FeatureTupleNamedTuple
ImmutableYesYes
Access by IndexYesYes
Access by NameNoYes
ReadabilityLowHigh
Memory EfficientYesYes
Object-Like BehaviorNoYes

NamedTuple vs Dictionary

FeatureNamedTupleDictionary
Memory UsageLowerHigher
Faster AccessYesSlightly Slower
ImmutableYesNo
Named FieldsYesYes
Best for Fixed DataYesNo

Advantages of NamedTuple

1. Improved Readability

person.name

is clearer than:

person[0]

2. Memory Efficient

Consumes less memory than dictionaries.

3. Faster Access

Field access is optimized.

4. Immutable

Protects data from accidental modifications.

5. Compatible with Tuples

Works anywhere a regular tuple is expected.


Common Mistakes

Forgetting to Import namedtuple

Person = namedtuple(
    "Person",
    ["name"]
)

Error:

NameError:
namedtuple is not defined

Correct:

from collections import namedtuple

Trying to Modify a NamedTuple

person.age = 30

This causes:

AttributeError

Use _replace() instead.


Best Practices

  • Use NamedTuple for fixed, structured data.
  • Use meaningful field names.
  • Use _replace() for updates.
  • Use _asdict() when converting to JSON.
  • Prefer NamedTuple over regular tuples when readability matters.

Conclusion

Python NamedTuple provides a powerful way to create lightweight, readable, and immutable data structures. It combines the speed and memory efficiency of tuples with the convenience of named attributes.

NamedTuple is ideal for storing records, configuration values, API responses, database rows, and any structured data where field names improve readability.

By mastering NamedTuple, you can write cleaner, more maintainable Python code while keeping performance high. 




Post a Comment

0 Comments