There's more...

As seen in the preceding examples, named tuples have special methods and attributes available to them, as well as the methods available to normal tuples. The namedtuple methods and attributes are denoted with an underscore prefix to ensure that they don't conflict with field names, as shown here:

  • <namedtuple>._make(iterable): A class method that creates a new instance from an existing sequence or iterable object:
      >>> t = [12, 34]      >>> Point._make(t)      Point(x=12, y=34)
  • <namedtuple>._asdict(): It returns an OrderedDict object that maps field names to corresponding values:
      >>> p = Point(x=12, y=34)      >>> p._asdict()      OrderedDict([('x', 11), ('y', 22)])>
  • <namedtupled>._replace(**kwargs): It returns an instance of the named tuple ...

Get Secret Recipes of the Python Ninja now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.