Python “Tuple+”: Named Tuples. Tuples are a powerful Python type — but… | by Marcin Kozak | Jan, 2024

Tuples are a powerful Python type — but named tuples even more so!

Marcin Kozak
Towards Data Science
Named tuples join the strengths of names and tuples. by Ainur Iman on Unsplash

The three most popular Python types are the list, the dictionary, and the tuple. Lists and dictionaries are mutable, meaning that their elements can be altered after creation. Tuples, on the other hand, are immutable, so they cannot be changed after creation. If you do need to modify the contents of a tuple, you must create a new instance with the desired and assign it to the same variable.

This article focuses on Python named tuples, a specialized type of tuple that combines the of regular tuples with the added flexibility of named fields. Compared to regular tuples, named tuples can make simpler, more readable and more maintainable — and even more Pythonic. However, you must be careful, as sometimes using named tuples excessively can inadvertently reduce code readability rather than enhance it.

Read on to learn more!

To understand named tuples, you have to first understand regular Python tuples. If you’re not familiar with them, I strongly advise you to first read the following two articles about this data type:

What’s fantastic about named tuples is that they like regular tuples: everything that works for a regular tuple will for a named tuple. But that’s not all, as named tuples offer additional — hence the moniker “tuple+”. Therefore, I’ll assume you’re familiar with the key concepts covered in these two articles above, and we’ll focus on the advantages of named tuples.

First and foremost, keep in mind that all tuples are immutable. You may find it easy to forget this crucial characteristic when you start…

Source link