10.12 Named Tuples

You’ve used tuples to aggregate several data attributes into a single object. The Python Standard Library’s collections module also provides named tuples that enable you to reference a tuple’s members by name rather than by index number.

Let’s create a simple named tuple that might be used to represent a card in a deck of cards. First, import function namedtuple:

In [1]: from collections import namedtuple

Function namedtuple creates a subclass of the built-in tuple type. The function’s first argument is your new type’s name and the second is a list of strings representing the identifiers you’ll use to reference the new type’s members:

In [2]: Card = namedtuple('Card', ['face', 'suit'])

We now have a new tuple type named ...

Get Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and The Cloud 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.