Python named tuple Code Example

Last Updated On Monday 12th Jul 2021
  • Tuple is an immutable and hashable list.
  • Named tuple is its subclass with named elements.

Example 1

	from collections import namedtuple
Point = namedtuple('Point', 'a b')
p = Point(5, y=6)# Point(a=5, b=6)
p[0]             # 5
p.a              # 5
getattr(p, 'b')  # 6
p._fields #('a', 'b')
	

Example 2

	from collections import namedtuple
Series = namedtuple('Name', 'Author')
series = Series('Doraemon', 'Fujiko Fujio')
f'{series.author}'           # 'Fujiko Fujio'
'{p.name}'.format(p=series)  # 'Doraemon'