Curriculum
In Python, a named tuple is a subclass of the built-in tuple data type that has named fields. Each field has a name and a position, and can be accessed using dot notation (like object attributes) or using indexing (like regular tuples). Named tuples are immutable like regular tuples, but their fields can be accessed by name, which makes them more readable and self-documenting.
Here’s an example of creating a named tuple in Python:
from collections import namedtuple
# Define a named tuple called "Person" with fields "name", "age", and "gender"
Person = namedtuple('Person', ['name', 'age', 'gender'])
# Create an instance of the Person named tuple
person1 = Person('Alice', 25, 'female')
# Access the fields of the person1 named tuple by name or by index
print(person1.name) # Alice
print(person1[1]) # 25
print(person1.gender) # female
In this example, we first import the namedtuple function from the collections module. We then define a named tuple called “Person” with fields “name”, “age”, and “gender” using the namedtuple function. The first argument of the function is the name of the named tuple, and the second argument is a list of field names.
We then create an instance of the Person named tuple called person1 by passing in values for the three fields in order. We can access the fields of the person1 named tuple by name or by index, just like with regular tuples.
Named tuples are particularly useful when you have a collection of related values that need to be passed around or manipulated together. By using named tuples, you can give meaningful names to each field and make your code more readable and self-documenting. Additionally, named tuples are lightweight and efficient, since they are implemented as regular tuples with some added functionality.