Python Namedtuples Tutorial – Complete Guide

Do you find working with tuples to be a hassle when it comes to maintaining and accessing data in Python? How about using a better, improved version of tuples called nametuples in Python!

What are Namedtuples in Python?

Namedtuples in Python are an enhanced version of the common tuple data structure. Unlike regular tuples, namedtuples are more like dictionaries where you can reference elements by a meaningful name instead of their index.

What are Namedtuples used for?

Namedtuples are highly efficient and useful for packaging data. They provide a perfect balance between dictionaries, which provide clear and readable code, and tuples, which are lightweight and faster in execution.

Why should I learn about Namedtuples in Python?

Namedtuples increase your code’s readability, as they allow you to access data elements by name instead of index. This makes your code easier to work with and understand. Learning namedtuples gives you an additional tool in your Python toolkit, allowing you to write more efficient code. They are particularly handy when there are a lot of elements in a tuple and you want to access them in a more human-readable way.

CTA Small Image

FREE COURSES AT ZENVA

LEARN GAME DEVELOPMENT, PYTHON AND MORE

AVAILABLE FOR A LIMITED TIME ONLY

How to create a Namedtuple

To create a namedtuple in Python, you need to import the namedtuple class from the collections module.
After that, you can define a namedtuple by providing a name for the type and the names of its fields.

Let’s look at an example:

from collections import namedtuple

#Creating a namedtuple
Person = namedtuple('Person', 'name age job')
p = Person(name='John', age=32, job='<a class="wpil_keyword_link" href="https://gamedevacademy.org/what-is-a-developer/" target="_blank" rel="noopener" title="Developer" data-wpil-keyword-link="linked">Developer</a>')

Now we have a new namedtuple ‘Person’, and an instance ‘p’ is created with the name ‘John’, age 32 and job ‘Developer’.

Accessing the elements of a Namedtuple

We can access the elements of the namedtuple using the dot operator with the field names.

#Accessing the elements of the namedtuple
print(p.name) # Output: John
print(p.age) # Output: 32
print(p.job) # Output: Developer

Using _replace() function

We use the _replace() function to change the values of the fields of a namedtuple.

#Using _replace function to change job of 'p'
p = p._replace(job='Senior Developer')
print(p) # Output: Person(name='John', age=32, job='Senior Developer')

This change doesn’t affect the original namedtuple, but creates a new one.

Converting Namedtuple to Dictionary

Sometimes, you might want to convert a namedtuple to a dictionary for better flexibility. Python namedtuples have a handy method for this: _asdict().

#Converting namedtuple to dictionary
person_dict = p._asdict()
print(person_dict) # Output: OrderedDict([('name', 'John'), ('age', 32), ('job', 'Senior Developer')])

Now, with ‘person_dict’, we can update, delete, or add more items. It should be noted that an OrderedDict maintains its sorted order.

Control Fields with Defaults

Sometimes, you want your namedtuple to have default values for certain fields. Here’s how you can achieve this:

from collections import namedtuple

#Creating a namedtuple with defaults
Person = namedtuple('Person', ['name','age','job'],defaults=['John',None,'Developer'])

#Access the defaults by creating an instance without providing all values
p = Person()
print(p) # Output: Person(name='John', age=None, job='Developer')

In this case, the defaults are applied from right to left when some elements are not provided.

Checking the Fields of Namedtuple

By using the _fields attribute of a namedtuple, you can get all the fields name.

print(p._fields) # Output: ('name', 'age', 'job')

Iterating through Namedtuple using _asdict()

As we learned, a namedtuple can be converted into the dictionary by using _asdict(). After conversion, we can iterate through elements.

for key, value in p._asdict().items():
    print(key,value)
# Output:
# name John
# age None
# job Developer

Adding elements to a Namedtuple

Adding elements to a namedtuple is much like appending an element to a tuple, which will create and return a new tuple.

from collections import namedtuple

#Create initial namedtuple
Person = namedtuple('Person', 'name age job')
p = Person(name='John', age=32, job='Developer')

#Adding elements
Person = namedtuple('Person', Person._fields + ('salary',))
p = Person(*p, 80000)
print(p) # Output: Person(name='John', age=32, job='Developer', salary=80000)

In the above code, the “*” operator is used to unpack the existing namedtuple into the new namedtuple, and ‘80000’ is added in the field ‘salary’. The whole operation creates a new namedtuple.

Deleting elements from a Namedtuple

Since tuple object does not support item deletion, the same applies to namedtuple. Rather, we create a new namedtuple excluding the element which we wish to delete.

#Deleting elements
Person = namedtuple('Person', 'name age')
p = Person(*p[:-1])
print(p) # Output: Person(name='John', age=32)

In the above code, *p[:-1] leaves out the last element during the creation of the new namedtuple. And voila, the ‘job’ field is gone now! The same method of slicing can be used to exclude multiple elements as well.

Where to go next

Having mastered namedtuples in Python, your journey in the Python world doesn’t have to end here. There’s so much more to learn and explore!

At Zenva, we offer the Python Mini-Degree, a comprehensive collection of courses that cover everything from the very basics, to advanced algorithms, object-oriented programming, game development, and even app development. The Mini-Degree includes exciting projects such as creating games, developing AI chatbots, and building apps.

This curriculum is tailor-made to suit both beginners just starting their coding journey and experienced programmers looking to enhance their skill set. What sets our courses apart is their project-based approach, guaranteeing not just theoretical knowledge, but also the practical experience needed to kickstart your coding career.

Keep learning

Our Python courses provide an all-encompassing Python learning path. The wide array of topics included ensures that you’ll have all the tools necessary to tackle any coding challenge that comes your way.

Ready for the next step in your coding journey? Join us and go from beginner to professional with Zenva!

Conclusion

In conclusion, Python namedtuples go a long way in enhancing the readability and efficiency of your Python code. With the right learning tools in hand, you can elevate your Python proficiency to new heights.

Embark on your next coding adventure with Zenva’s Python Mini-Degree. The course takes you from the fundamentals of Python programming all the way to creating intricate projects. Dive into the exciting world of Python programming and discover its vast potential. Happy coding!

FREE COURSES

Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Unreal, Python, Godot and more.