When you need to represent a list of identical objects with different values, you start with a list of tuples. It’s an efficient way to hold a collection of related data. Tuples are like structures or records in other languages, but indexed with integers, like lists. You can build a list named people, where each element is a tuple of three elements: first name, last name, and zip code. To get the zip code for the first element, you can use people.
The problem comes when you want to read in a file where each line has 17 fields. It gets really hard to remember which index is for which field. At this point, many programmers create a class with read-only properties for this purpose, so they can say class.field (e.g., people.first_name, people.last_name, etc.). Such a class has no methods; it only exists to store the data.
It’s overkill to use a class for this purpose. Python provides an elegant solution – named tuples. A named tuple is exactly like a normal tuple, except that the fields can also be accessed by .fieldname. Named tuples are still immutable, you can still index elements with integers, and you can iterate over the elements. With a named tuple, you can say record.first_name, record.last_name, as with a class, but without the extra code of a class. There’s no need to write all the property definitions.
Creating a Named Tuple
To create a named tuple, import the namedtuple class from the collections module. The constructor takes the name of the named tuple (which is what type() will report), and a string containing the fields names, separated by whitespace. It returns a new namedtuple class for the specified fields. To use it, call the new class with all the values (in order) as parameters. Remember, the tuple is still immutable. You can’t change it or add fields later. All fields must be supplied.
Remember, when you need a structure with field names, use a named tuple.
>>> from collections import namedtuple >>> Person = namedtuple('Person', 'first_name last_name zip_code') >>> p1 = Person('Joe', 'Schmoe', '93002') >>> p1.first_name 'Joe' >>> p1 'Joe' >>> p1.zip_code '92002' >>> len(p1) 3 >>> type(p1) <class '__main__.Person'> >>>
Author: John Strickler, one of Accelebrate’s Python instructors
Accelebrate offers private, on-site Python training.