What is a Python namedtuple?
a) A subclass of tuples that allows for named fields
b) A built-in function for creating dictionaries
c) A specialized list that can hold unique items only
d) A function used for creating iterators
Answer:
a) A subclass of tuples that allows for named fields
Explanation:
A namedtuple
in Python is a subclass of tuples that allows for named fields, making it easier to access elements by name rather than by index. Namedtuples are immutable and can be used in place of regular tuples, offering better code readability and maintainability.
from collections import namedtuple
# Defining a namedtuple for a point in 2D space
Point = namedtuple('Point', ['x', 'y'])
p = Point(x=10, y=20)
print(p.x) # Output: 10
print(p.y) # Output: 20
In this example, a namedtuple Point
is defined with fields x
and y
, allowing you to access these values using dot notation.
Namedtuples are particularly useful when working with structured data, as they provide a clear and concise way to represent and access the data fields.