The Python Geek

The Named Tuple

A glorious discovery from the collections module

The Named Tuple

Created: Thu 29 November 2018

Tags: Python


Introduction

The named tuple is part of the collections module. It is an under-utilized feature that provides a good alternative to a class in the right situation. It's a tuple extension that has a class-like feel to it. Essentially, you give field names to the members of a tuple. This can make your code more readable.

Remind me what a tuple is

A tuple is a sequence, like a list, except that is immutable (cannot be changed). So you can iterate through a tuple or you can index it.

a = (1,2,3) # tuple

print(a[0]) # 1

for i in a:
    print(i) # 1 2 3

a[0] = 100 # error, immutable

So for example, say you have a tuple with name, age and profession. You would have to remember the index for each of these. Below we unpacked the tuple (which is a cool python feature), but as you see we accidentally put profession in the wrong position. So our printed sentence is a wreck.

person = ('Barry','40','Developer')

name,profession,age = person

# Barry is a 40 and is Developer years old
print("{} is a {} and is {} years old".format(name,profession,age))

Named Tuple!

Best way to learn named tuple is with an example. We will continue from the last one. What we will find out is that named tuples are easy to create and instantiate, are also immutable and data is easily accessed by the dot operator using attribute names.

So here we import namedtuple from the collections module. We define Person using namedtuple. This provides us a factory function to create instances. Inside of namedtuple we pass in a string with desired attributes separated by spaces. You can also do this via a list of strings instead. When this definition is complete we create an instance called p. It is then shown how we can access the attributes. We now have a correct sentence.

from collections import namedtuple

Person = namedtuple('Person', 'name age profession')
p = Person('Barry','40','Developer')

# access attribute data through dot operator
print(p.name) # Barry
# can still use index
print(p[0]) # Barry

# p.name = 'Jerry' # Error, immutable

# Barry is a Developer and is 40 years old
print("{} is a {} and is {} years old".format(p.name,p.profession,p.age))

Conclusion

The named tuple provides a nifty construct to provide names to elements in a tuple. It comes with the same fundamental properties of tuples like it being immutable, having indexing capabilities, and iteration. The named tuple can make your code more readable by you and others.