Skip to content
Rezha Julio

Python

Enhance your tuples

1 min read

Standard Python `tuple`s are lightweight sequences of immutable objects, yet their implementation may prove inconvenient in some scenarios

Standard Python tuples are lightweight sequences of immutable objects, yet their implementation may prove inconvenient in some scenarios.

Instead, the collections module provides an enhanced version of a tuple, namedtuple, that makes member access more natural (rather than using integer indexes).

Import namedtuple:

from collections import namedtuple

Create a namedtuple object:

point = namedtuple('3DPoint', 'x y z')
A = point(x=3, y=5, z=6)
print(A)
# 3DPoint(x=3, y=5, z=6)

Access a specific member:

print(A.x)
# 3

Because namedtuples are backwards compatible with normal tuples, member access can be also done with indexes:

print(A[0])
# 3

To convert a namedtuple to a dict (actually an OrderedDict):

print(A._asdict())
#OrderedDict([('x', 3), ('y', 5), ('z', 6)])

Related Posts


Previous Post
Get more with collections!
Next Post
Looping techniques in Python