C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Create: We create a namedtuple by using the Employee class name returned by collections.namedtuple.
Title: At the end of the program we access the "title" field with the syntax e.title: no index is required.
Python program that creates a namedtuple
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)
Output
Employee(id=1, title='engineer', salary=10000)
Title is engineer
Tip: The make method fills namedtuple fields based on the order of the list's elements. So we must be careful with ordering.
ListPython program that uses _make method
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)
Output
Style(color='red', size=10, width=15)
Version 1: This version of the code creates a namedtuple with 2 items in it. The code tests the first item in an if-statement.
IfVersion 2: Here we create a tuple (not a namedtuple). We test the first item with an if-statement here as well.
Result: I found that namedtuple is several times slower in creation than a regular tuple.
Python program that benchmarks namedtuple, tuple
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())
Output
1403288922.718007
1403288936.606831 namedtuple = 13.89 s
1403288939.667796 tuple = 3.06 s
Quote: Named tuple instances do not have per-instance dictionaries, so they are lightweight and require no more memory than regular tuples.
Collections, namedtuple: python.org