What are "named tuples" in Python?
"Named tuples" in Python are a subclass of the built-in tuple
type, but with the added ability to access elements by name rather than just by index. They are defined using the collections.namedtuple()
function, which takes two arguments: the name of the new tuple class and a string of space-separated field names.
Here is an example code snippet that demonstrates how to use a named tuple:
from collections import namedtuple
# Define a named tuple type called "Person" with fields "name" and "age"
Person = namedtuple("Person", "name age")
# Create an instance of the Person named tuple
p = Person("Alice", 25)
# Access the fields by name
print(p.name) # Output: "Alice"
print(p.age) # Output: 25
# Access the fields by index
print(p[0]) # Output: "Alice"
print(p[1]) # Output: 25
You can also use the _fields
attribute of the named tuple class to get a tuple of the field names, and the _asdict()
method to get an ordered dictionary from a named tuple.