With tuples we store small groups of related fields together. A Point
tuple, for example will have 2 coordinates: X and Y. The coordinates are part of a single unit.
To use namedtuple, we import the collections module. We specify the Type name. And we pass a string
list of all the field names—these can then be directly used as fields.
Here we create an Employee namedtuple with 3 fields. We pass a list to collections.namedtuple
to specify field names id, title and salary.
class
name returned by collections.namedtuple
.e.title
: no index is required.import collections # Specify the Employee namedtuple. Employee = collections.namedtuple("Employee", ["id", "title", "salary"]) # Create Employee instance. e = Employee(1, "engineer", 10000) # Display Employee. print(e) print("Title is", e.title)Employee(id=1, title='engineer', salary=10000) Title is engineer
Namedtuple offers extra methods—one of them is _make. With _make()
we create a namedtuple from an iterable
(like a list). The list elements are turned into tuple fields.
import collections # A namedtuple type. Style = collections.namedtuple("Style", ["color", "size", "width"]) # A list containing three values. values = ["red", 10, 15] # Make a namedtuple from the list. tuple = Style._make(values) print(tuple)Style(color='red', size=10, width=15)
This benchmark tests how long it takes to create a namedtuple versus a regular tuple. The results are not encouraging for namedtuple.
if
-statement.if
-statement here as well.import collections import time # The namedtuple instance. Animal = collections.namedtuple("Animal", ["size", "color"]) print(time.time()) # Version 1: create namedtuple. i = 0 while i < 10000000: a = Animal(100, "blue") if a[0] != 100: raise Exception() i += 1 print(time.time()) # Version 2: create tuple. i = 0 while i < 10000000: a = (100, "blue") if a[0] != 100: raise Exception() i += 1 print(time.time())1403288922.718007 1403288936.606831 namedtuple = 13.89 s 1403288939.667796 tuple = 3.06 s
Even though namedtuple does not use excess memory, it involves more steps to initialize. And it requires a separate module (collections), making it harder to access.
In most programs, a tuple is a better choice than a named tuple. And for large groups of keys, a dictionary or set may be better. Namedtuple is limited in its use.