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


PYTHON PROGRAMMING

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

Named tuples join the strengths of names and tuples. Photo by Ainur Iman on Unsplash

The three most popular Python data 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 changes and assign it to the same variable.

This article focuses on Python named tuples, a specialized type of tuple that combines the power of regular tuples with the added flexibility of named fields. Compared to regular tuples, named tuples can make code 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 function like regular tuples: everything that works for a regular tuple will work for a named tuple. But that’s not all, as named tuples offer additional features — 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

Be the first to comment

Leave a Reply

Your email address will not be published.


*