Skip to Content
Secret Recipes of the Python Ninja
book

Secret Recipes of the Python Ninja

by Cody Jackson
May 2018
Intermediate to advanced content levelIntermediate to advanced
380 pages
9h 37m
English
Packt Publishing
Content preview from Secret Recipes of the Python Ninja

How to do it...

It doesn't get much better than the official documentation, so here is an example from https://docs.python.org/3/library/collections.html#collections.namedtuple:

  1. Make namedtuple:
      >>> from collections import namedtuple      >>> Point = namedtuple("Point", ["x", "y"])
  1. Make a new instance of the namedtuple. You can use positional or keyword arguments:
      >>> p = Point(11, y=22)
  1. The new namedtuple can be indexed like a normal tuple:
      >>> p[0] + p[1]      33
  1. It can also be unpacked like a regular tuple:
      >>> x, y = p      >>> x, y      (11, 22)
  1. Tuple objects can be accessed by their assigned names instead of index:
      >>> p.x + p.y      33
  1. Because __repr__ is provided automatically, calling the namedtuple instance provides all information about ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

The Expanding World of Python

The Expanding World of Python

Dane Hillard

Publisher Resources

ISBN: 9781788294874Supplemental Content