Python Named Tuples
What are Named Tuples in Python?
Named tuples are a way to access the items of a tuple using names instead of index.
To access a typical tuple, we use index as shown in the following program.
# Initialize tuple
my_tuple = ('Apple', 20)
# Access items in tuple using index
print(my_tuple[0])
print(my_tuple[1])
Using named tuples, we can define a name to each of the item in the tuple, and read them using these names.
from collections import namedtuple
# Define a named tuple
Person = namedtuple('Person', ['name', 'age'])
# Initialize the named tuple
person_1 = Person(name='Apple', age=20)
# Access items in tuple using index
print(person_1.name)
print(person_1.age)
This example is quite illustrative on its own on how to use namedtuple() to create a namedtuple, and then use it in a Python program. But, we will go in detail.
Import namedtuple
To use namedtuple in Python, you have to import it from collections module.
Use the following import statement in your program, if you are using namedtuple.
from collections import namedtuple
Define a namedtuple
To define a namedtuple, use namedtuple() function.
def namedtuple(
typename: str,
field_names: str | Iterable[str],
*,
rename: bool = False,
module: str | None = None,
defaults: Iterable[Any] | None = None
)
The first argument is the typename, just like a custom class name that you would give to create a class type.
The second argument is an iterable with the names of the fields in the named tuple.
From, our previous example, let us write that piece of code which defines a named tuple Person.
namedtuple('Person', ['name', 'age'])
The first argument 'Person' is the typename.
The second argument ['name', 'age'] is a list of names for the items in the tuple.
This namedtuple() function returns a type object. It's like a blueprint. You can store it and then use it to create named tuples of this type.
Person = namedtuple('Person', ['name', 'age'])
We have stored the type returned by namedtuple() in Person. So that we can easily remember which type is which. You can rename it differently if you want to, like say, Student.
Student = namedtuple('Person', ['name', 'age'])
Create an object of namedtuple type
We have seen how to define a named tuple. We have created one, that is Person. Let us use that and create an object of this Person type named tuple.
We have to use the type Person, and then specify the named parameters as shown in the following code.
person_1 = Person(name='Apple', age=20)
The syntax looks similar to creating a class object with named parameters. Here, we have created a Person type object with the specified named parameters, and then assigned it to a variable person_1.
Accessing fields of a namedtuple
You can use the names of the fields to access the values, from a namedtuple object.
For example, we have defined and created objects of type Person, which has named fields name and age.
To access the fields name and age of type Person, we can use dot operator as shown in the following.
person_1.name
person_1.age
Complete Program of namedtuple Person
Let us put back all the things together that we have seen in the above sections of defining a namedtuple, creating objects, and reading the values of the fields.
Python Program
from collections import namedtuple
# Define a named tuple
Person = namedtuple('Person', ['name', 'age'])
# Initialize the named tuple
person_1 = Person(name='Apple', age=20)
# Access items in tuple using index
print(person_1.name)
print(person_1.age)
Output
Apple
20
namedtuple is immutable
Just like a tuple, namedtuple is immutable. We cannot modify a namedtuple, not its fields.
After initializing an object, let us try to assign a new value to one of the fields, say name.
Python Program
from collections import namedtuple
# Define a named tuple
Person = namedtuple('Person', ['name', 'age'])
# Initialize the named tuple
person_1 = Person(name='Apple', age=20)
# Try assigning a new value to name field
person_1.name = 'Banana'
# Access items in tuple using index
print(person_1.name)
print(person_1.age)
Output
Traceback (most recent call last):
File "/Users/pythonexamplesorg/main.py", line 10, in <module>
person_1.name = 'Banana'
^^^^^^^^^^^^^
AttributeError: can't set attribute
We cannot set attribute of a namedtuple, and the interpreter raises AttributeError exception.
Summary
In this tutorial, we learned about named tuples in Python, how to define namedtuple, how to initialize a namedtuple, how to access the fields of a namedtuple, etc., with example programs.