TonyW
TonyW

Reputation: 18875

How to access elements in nametuples in python?

I'm confused about accessing elements in namedtuple in python, say I have

Container = namedtuple('Container', ('mac_0', 'mac_1'))

Can I use Container[0] and Container[1] to access the first element mac_0 and the second element mac_1 ?

Upvotes: 3

Views: 1051

Answers (1)

alecxe
alecxe

Reputation: 473853

You can access elements either by index, or by name (documentation):

>>> from collections import namedtuple
>>> Container = namedtuple('Container', ('mac_0', 'mac_1'))
>>> container = Container(mac_0=1, mac_1=2)
>>> container[0]
1
>>> container[1]
2
>>> container.mac_0
1
>>> container.mac_1
2

Upvotes: 5

Related Questions