Why should you use namedtuple instead of a tuple?

Why should you use namedtuple instead of a tuple?

Hi there guys! You might already be acquainted with tuples. A tuple is a lightweight object type which allows to store a sequence of immutable Python objects. They are just like lists but have a few key differences. The major one is that unlike lists, you can not change a value in a tuple. In order to access the value in a tuple you use integer indexes like:

man = (‘Ali’, 30)
print(man)
# Output: Ali

Well, so now what are namedtuples? They turn tuples into convenient containers for simple tasks. With namedtuples you don’t have to use integer indexes for accessing members of a tuple. You can think of namedtuples like dictionaries but unlike dictionaries they are immutable.

from collections import namedtuple

Animal = namedtuple(‘Animal’, ‘name age type’)
perry = Animal(name=”perry”, age=31, type=”cat”)

print(perry)
# Output: Animal(name=”perry”, age=31, type=”cat”)

print(perry.name)
# Output: ‘perry’

As you can see that now we can access members of a tuple just by their name using a .. Let’s disect it a little more. A named tuple has two required arguments. They are the tuple name and the tuple field_names. In the above example our tuple name was ‘Animal’ and the tuple field_names were ‘name’, ‘age’ and ‘cat’.

Namedtuple makes your tuples self-document. You can easily understand what is going on by having a quick glance at your code. And as you are not bound to use integer indexes to access members of a tuple, it makes it more easy to maintain your code.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store