0
0
PythonConceptBeginner · 3 min read

What is Named Tuple in Python: Simple Explanation and Example

A namedtuple in Python is a special kind of tuple that allows you to access its elements by name instead of only by position. It works like a simple class with named fields, making your code easier to read and maintain.
⚙️

How It Works

A namedtuple is like a regular tuple but with named slots for each value. Imagine a tuple as a list of items where you remember each item by its position number, like the first, second, or third. A named tuple lets you give each position a name, like name, age, or color, so you can use those names to get the values instead of counting positions.

Under the hood, Python creates a small class for the named tuple type. When you create a named tuple, you get an object that stores values and lets you access them by name, just like attributes in a class. This makes your code clearer because you don’t have to remember which position means what.

💻

Example

This example shows how to create and use a named tuple to store information about a person.

python
from collections import namedtuple

Person = namedtuple('Person', ['name', 'age', 'city'])

p = Person(name='Alice', age=30, city='New York')

print(p.name)  # Access by name
print(p[1])    # Access by position
print(p)
Output
Alice 30 Person(name='Alice', age=30, city='New York')
🎯

When to Use

Use named tuples when you want to group related data together but keep your code simple and readable. They are great for small, fixed collections of items where you want to access elements by name without writing a full class.

For example, named tuples are useful for representing points in 2D space, records from a database, or any data where you want clear labels for each value. They are faster and use less memory than regular classes, making them handy for lightweight data structures.

Key Points

  • Named tuples provide named fields for tuple elements.
  • They improve code readability by replacing index access with names.
  • They behave like immutable objects, so their values cannot be changed.
  • Named tuples are memory efficient compared to regular classes.
  • They are created using collections.namedtuple.

Key Takeaways

Named tuples let you access tuple elements by name, making code clearer.
They are simple, immutable, and memory-efficient data containers.
Use named tuples for small, fixed groups of related data.
They are created with collections.namedtuple and behave like lightweight classes.