May 2019
Beginner
528 pages
29h 51m
English
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 ...
Read now
Unlock full access