Named Tuples

Named Tuples is a subclasses of tuple enhanced with field names and a class name. It helps debugging.

namedtuple tale exactly the same amount of memory as tuples because the field names are stored in the class.

They use less memory than a regular object because they don't store attributes in a per-instance _dict_

List v.s. Tuple

tuple supports all list methods that do not involve adding or removing items, with one exception — tuple lacks the re versed method.

However, that is just for optimization; reversed(my_tuple) works without it.

Example

from collections import namedtuple
Card = namedtuple('Card', ['rank', 'suit'])
a_heart =Card(rank="A", suit="heart")
print(a_heart.rank)
>>> A
print(a_heart.suit)
>>> heart
print(a_heart[0])
>>> A
print(a_heart[1])
>>> heart

Last updated

Was this helpful?