Junior
How is access to elements of namedtuple in Python implemented?
sobes.tech AI
Answer from AI
Accessing elements of a namedtuple in Python is done by field name or by index.
By field name:
// Creating a namedtuple
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
// Accessing elements by name
x_coord = p.x
y_coord = p.y
By index:
// Creating a namedtuple (using the same 'Point' namedtuple from the previous example)
// from collections import namedtuple
// Point = namedtuple('Point', ['x', 'y'])
// p = Point(10, 20)
// Accessing elements by index
x_coord = p[0]
y_coord = p[1]
When iterating:
// Creating a namedtuple (using the same 'Point' namedtuple from the previous example)
// from collections import namedtuple
// Point = namedtuple('Point', ['x', 'y'])
// p = Point(10, 20)
// Iterating over elements
for value in p:
print(value)