Named Tuple in Python: Simple Guide with Practical Examples

Introduction

Named tuples are a great tool if you’re learning Python and want to organize data more clearly than you would with regular tuples. This tutorial will help you understand what named tuples are, how they differ from regular tuples, and how to use them through hands-on examples. Perfect for beginner-to-intermediate learners who want clear, runnable Python code.

Simple way

Named tuples are similar to regular tuples but also allow access to fields by name as well as position. They enhance clarity while maintaining immutability. This tutorial covers the basics, along with some original Python code examples to get you up and running quickly.

Named Tuple in Python

What is a Named Tuple in Python?

A named tuple in Python is a subclass of Python’s standard tuple where each position is named so you can access elements by label, rather than by index. Therefore, it improves code readability and makes data structures self-documenting. Similar to regular tuples, they are immutable to prevent accidental changes in values.

Named tuples come from the collections module, in particular a factory function called namedtuple. This means you create a new, class-like structure dynamically that behaves like a tuple but with named fields.

Why Use Named Tuples?

  • Access elements by name, not just index.
  • Improving code readability and maintainability.
  • Store immutability of tuples.
  • Save memory compared to using full classes.
  • Useful for small, simple data structures.

Named tuples are an elegant way to represent simple records without all the overhead of a class.

Creating a Named Tuple: Basic Example

from collections import namedtuple

# Define a named tuple in Python 'Book' with fields title, author, and year
Book = namedtuple('Book', ['title', 'author', 'year'])

# Instantiate Book
my_book = Book(title="Python 101", author="Jane Doe", year=2025)

# Access fields by name
print(my_book.title)  # Output: Python 101
print(my_book.author) # Output: Jane Doe

Note: The code defines a named tuple for books and prints the title of the book and its author.

Accessing Named Tuple Fields

There are two ways to access fields: by name and by index.

print(my_book.year)      # Access by field name, output: 2025
print(my_book[2])        # Access by index, output: 2025

Named tuples also support unpacking:
title, author, year = my_book
print(title)  # Python 101

Named Tuple Methods and Properties

Named tuples have helpful methods such as _replace() for “modifying,” returning a new named tuple with updated fields:

new_book = my_book._replace(year=2026)
print(new_book)  # Book(title='Python 101', author='Jane Doe', year=2026)

You can also convert a named tuple to a dictionary:

print(my_book._asdict())
# Output: {'title': 'Python 101', 'author': 'Jane Doe', 'year': 2025}

These built-in methods make named tuples even more powerful.

Original Example: Store and Display Employee Data

Suppose you want to keep employee records concise and readable:

Named Tuple in Python
from collections import namedtuple

Employee = namedtuple('Employee', ['name', 'id', 'department'])

employee1 = Employee("Sam Wilson", 101, "IT")
employee2 = Employee("Lisa Ray", 102, "HR")

employees = [employee1, employee2]

for emp in employees:
    print(f"{emp.name} (ID: {emp.id}) works in {emp.department}")

Expected Output:

Sam Wilson (ID: 101) works in IT
Lisa Ray (ID: 102) works in HR

Note: This example shows how named tuples neatly represent employee records.

Named Tuple with Default Values

By default, named tuples don’t support default values directly. You can extend them or use a workaround:

from collections import namedtuple

# Create namedtuple with defaults via subclassing
class Employee(namedtuple('Employee', ['name', 'id', 'department'])):
__slots__ = ()
def __new__(cls, name, id, department='General'):
return super(Employee, cls).__new__(cls, name, id, department)

emp1 = Employee('John', 1)
emp2 = Employee('Jane', 2, 'Finance')

print(emp1) # Employee(name='John', id=1, department='General')
print(emp2) # Employee(name='Jane', id=2, department='Finance')

This trick gives you immutable named tuples with default values.

Immutability and Named Tuples

Named tuples are immutable, meaning that once created, you cannot change their values:

try:
my_book.title = "Python Basics"
except AttributeError as e:
print(e) # Output: can't set attribute

If you need to “update” data, use the _replace() method which returns a new named tuple:

updated_book = my_book._replace(title="Python Basics")
print(updated_book)

Advanced: Named Tuples in Function Returns

Named tuples are great when you need to return multiple values with names from functions, as that greatly helps with clarity:

from collections import namedtuple

Result = namedtuple('Result', ['quotient', 'remainder'])

def divmod_namedtuple(a, b):
    q, r = divmod(a, b)
    return Result(q, r)

result = divmod_namedtuple(20, 6)
print(f"Quotient: {result.quotient}, Remainder: {result.remainder}")

Text:
Quotient: 3, Remainder: 2

This way, the returned values become self-describing and your code is easier to read and maintain.

Comparison: Named Tuple vs Dictionary vs Class

FeatureNamed Tuple in PythonDictionaryClass
ImmutabilityYesNoUsually mutable
Access by nameYes (dot notation)Yes (keys)Yes (attributes)
Memory efficiencyMore efficientLess efficientDiffering
Syntax simplicityClean & compactSimpleMore verbose
UsabilityGood for fixed fieldsGood for dynamic dataGood for complex behavior

Named tuples strike a good balance in case of fixed sets of related values, using immutability with clarity.

Practical Tips for Using Named Tuple in Python

Here are some personal tips that can help you get the most out of named tuple in Python:

  • Use named tuple in Python when you want immutability but easy-to-read code.
  • For large datasets, consider alternatives like dictionaries or data classes, but for smaller records, named tuple in Python is extremely handy.
  • Always use descriptive field names in your named tuple in Python to maximize code clarity.
  • Test your named tuple in Python code snippets to confirm expected outputs for all fields and methods.

FAQs

Q1: What is a named tuple in Python?
A named tuple in Python is an immutable, tuple-like object with named fields accessible by attribute lookups. This improves code readability.

Q2: How do I create a named tuple in Python?
Use namedtuple from collections module:
MyTuple = namedtuple(‘MyTuple’, [‘field1’, ‘field2’])

Q3: Can you change the value of a named tuple field?
No, named tuples are immutable. To create a new named tuple with updated values, use _replace().

Q4: In what ways is a named tuple better than a dictionary?
They use less memory, have fixed fields, and support attribute-style access, which makes the code cleaner.

Q5: Can named tuples have default values?
Not directly, but you can subclass them to add defaults or use other tricks.

For more reference:


if not the read more about this topic then check the link  Named tuple in python

related topics:

Is Tuple Mutable in Python? In-depth Explanation
Difference Between List Tuple Set and Dictionary in Python
Tuple Methods in Python with Practical Examples
What is Tuple in Python with Example
What Is Set in Python | with Example  

Leave a Reply

Your email address will not be published. Required fields are marked *