Kodeclik Blog

Named Tuples in Python

Named tuples are a type of tuple that allows you to access elements by name rather than by index. They're similar to classes in that they have attributes that can be accessed using dot notation, but they're immutable like regular tuples. This means that once created and assigned you cannot modify their values. However, you can create new instances of them with different values if you need to.
To understand named tuples, lets review “unnamed” tuples, i.e., the usual way of working with tuples in Python. Lets create a tuple to denote books; a book has a name, author, year, and publisher.
In the above program we are creating a tuple in variable “HarryPotter1” (denoting the first book in the Harry Potter series) containing four attributes of the corresponding book. The output is:
To access individual facets of the book, we do:
The output now is:
While this is useful, note that the above code is not particularly user-friendly. You will need to remember whether the author is the second field or the third field and use the corresponding index (taking care to remember that they begin at 0, not 1).
The idea of a named tuple in Python is to make the access of data elements easier so that we can refer to them by name rather than position. Named tuples are not standard in Python so we will have to import them from the collections module.
Here is basic code to illustrate how named tuples work:
The output will be:
Note that the first line of the output prints the tuple with a Book() prefix surrounding it, denoting that this is a named tuple. The next two lines print the author and publisher respectively.
The interesting thing about named tuples is that you can still access them by index, eg;
But recall that named tuples are immutable just like regular tuples, so you cannot modify the year or the author attribute once the tuple has been assigned. Thus the following code:
will yield:
In conclusion, named tuples are a type of Python tuples that allows you to access elements by name as well as by index. They are similar to classes in that they have attributes that can be accessed using dot notation; however, they're immutable like regular tuples. When working with large programs where you need to be able to access data elements by both name and index frequently, named tuples can be very useful.
If you liked this blogpost, learn about unpacking tuples in Python.
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2024. All rights reserved.