TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Python Namedtuple Example

This Python example uses the namedtuple type from the collections module. A namedtuple is a tuple with field names.

Namedtuple. With tuples we store small groups of related fields together.

A Point tuple, for example will have two 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.

An example. Here we create an Employee namedtuple with three fields. We pass a list to collections.namedtuple to specify field names id, title and salary.

Create: We create a namedtuple by using the Employee class name returned by collections.namedtuple.

And: At the end of the program we access the "title" field with the syntax e.title: no index is required.

Based on:

Python 3

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

Make method. 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.

Tip: The make method fills namedtuple fields based on the order of the list's elements. So we must be careful with ordering.

List

Python 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)

Creation time benchmark. This benchmark tests how long it takes to create a namedtuple versus a regular tuple. The results are not encouraging for namedtuple.

Note: I found that namedtuple is about four times slower in creation than a regular tuple.

Also: With a JIT compiler like PyPy, namedtuple was more competitive but still slower.

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())

Results

1403288922.718007
1403288936.606831  namedtuple = 13.89 s
1403288939.667796  tuple      =  3.06 s

Research. The Python documentation provides information about namedtuples. These are implemented in a similar way to regular tuples. So they do not use excess memory.

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

A comparison. 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.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf