logo
Python Data Structures - Interview Questions and Answers
What are named tuples, and when should you use them?
Named Tuples in Python

A named tuple is a special type of tuple provided by the collections module that allows named fields, making them more readable and self-documenting compared to regular tuples.


1. Why Use Named Tuples?
  • Improves code readability by accessing elements by name instead of index.
  • Immutable, just like regular tuples.
  • Memory-efficient compared to dictionaries (uses less space).
  • Useful for lightweight data structures like database records, coordinates, or configurations.

2. Creating a Named Tuple

You can create a named tuple using collections.namedtuple().

Example: Using Named Tuples for a Point (x, y)
from collections import namedtuple

# Define a named tuple called 'Point' with fields 'x' and 'y'
Point = namedtuple("Point", ["x", "y"])

# Create a point instance
p = Point(3, 4)

# Access values by name instead of index
print(p.x)  # Output: 3
print(p.y)  # Output: 4

# Named tuple is still a tuple, so it supports indexing
print(p[0])  # Output: 3

* More readable than a regular tuple (p.x instead of p[0]).


3. Named Tuples vs. Dictionaries
Feature Named Tuple Dictionary
Memory usage Less (optimized like a tuple) More (stores keys & values)
Access speed Faster (tuple-like) Slightly slower
Mutability Immutable Mutable
Readability (p.x instead of p['x']) Good, but longer syntax

4. Extra Features of Named Tuples
a) Assigning Default Values with defaultdict
from collections import namedtuple

# Define a named tuple with default values
Person = namedtuple("Person", ["name", "age", "city"])
p1 = Person("Alice", 25, "New York")

print(p1.name)  # Output: Alice
b) Converting Named Tuple to Dictionary
print(p1._asdict())  # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}

* Easily convert to a dictionary!

c) Replacing Values with _replace()
p2 = p1._replace(age=26)  
print(p2)  # Output: Person(name='Alice', age=26, city='New York')

* Creates a new modified instance (since tuples are immutable).


5. When Should You Use Named Tuples?

* For lightweight, immutable data structures (e.g., coordinates, database rows).
* When you need dictionary-like access but with better performance.
* For cleaner, self-documenting code.