Python Collections: namedtuple and deque make simple

Posted by Marta on January 24, 2021 Viewed 3034 times

Card image cap

There is not much documentation about Python collections besides the official documentation. Therefore, it isn’t easy to understand when to use Python collections and the differences with the built-in collections like list, set, dictionary, etc.

With this article you will learn the different two python collections: namedtuple and deque, use them, and the critical benefits versus the similar built-in collections.

It is important to note these collections were deprecated from version 3.3 and removed from Python in version 3.10. Nevertheless, it is useful to understand how they work since you might find them when reading Python code.

Let’s dive in!

Why more python collections?

Since Python already has collections like list, set, tuple, dictionary, etc., why is there another set of collections? The main reason is that this collection has some functionality gaps. As a result, Python released the library collections, which attempt to cover these functionality gaps.

namedtuple()

This collection helps you to create classes on the fly, without needing to define the class previously. It has limitations since you aren’t able to add methods to these classes. However, if you only need the class as a data container with no specific methods, this collection is a great option.

Find Python documentation here

Create a class with namedtuple()

Let’s see how to create a class using namedtuple(). The two mandatory parameters are first the name of our class, and second a list of the fields that the class will contain. For instance, let’s say you want to create a class Circle with two fields: radius and color. See below the code to achieve it:

Circle = collections.namedtuple('Circle',['radius','color'])
circle1=Circle(radius=10,color='Blue')

print(type(circle1))
print(circle1)

Output:

>>><class '__main__.Circle'>
>>>Circle(radius=10, color='Blue')

In line 1, the code will create the Circle class, and in the next line, it creates an object of this class; in other words, it will instantiate the class.

Access fields

One of the benefits of the namedtuple classes is its flexibility. You can access the fields by field name and index, unlike regular classes that only allow access by field name. Accessing fields by index also implies that fields are iterable.

circle1=Circle(radius=10,color='Blue')
print(circle1.radius)
print(circle1[0])

Output:

>>>10
>>>10

See below how to iterate over the class attributes:

circle1=Circle(radius=10,color='Blue')
for field in circle1._fields:
    print(circle1.__getattribute__(field))

Output:

>>>10
>>>Blue

Convert Dictionary to Object

Another handy operation is converting a dictionary to an object. Why is this useful? For instance, when you receive data in JSON format. NameTuple() allow you to convert the JSON string into Python object. See below at line 5 how to convert a dictionary to object.

circle_dict = { 'radius': 4,'color':'Red'} # Dict

circle_class = collections.namedtuple('Circle',['radius','color']) # Class

circle2=circle_class(**circle_dict) # Convert dict to object 
print(circle2)

Output:

>>> Circle(radius=4, color='Red')

Convert Object to Dictionary

And the reverse operation is also available. You could convert a Python object to a dictionary calling the _asdict() method. See an example below:

Circle = collections.namedtuple('Circle',['radius','color'])
circle1=Circle(radius=10,color='Blue')

print(circle1._asdict())

Output:

>>>OrderedDict([('radius', 10), ('color', 'Blue')])

deque collection

This deque collection works as a list. Providing some advantages like appending to both sides of the list efficiently, not only at the end.

How is this useful? For instance, imagine you would like to simulate a queue of people waiting to onboard a plane. Usually, you will add people at the end, but there might be a particular case, for instance, priority boarding, and that passenger should be added at the front of the queue as they arrived. Using a deque collection, you could easily replicate this behavior.

Create a deque

You can create or instantiate a new deque simply calling the deque() method passing as a parameter any variable that is iterable, like a String, a list, etc. For instance:

deque1 = collections.deque([1,2,3,4,5])
deque2 = collections.deque('qwsedrf')
print(deque1)
print(deque2)

Output:

deque([1, 2, 3, 4, 5])
deque(['q', 'w', 's', 'e', 'd', 'r', 'f'])

Once you create a deque, all list like operations are available: append(), clear(), copy(), count(), extend(), etc but there are three more operations that make this collections special: appendleft(), popleft() and extendleft(). Let’s see how to use each.

appendleft() operation

This operation will add an element to the front of the list in O(1) efficiency time, in other words, really, really fast. If you were using a list, the only operation available is append(), and to add an element at the beginning, you will need to shift all elements one place to the right.

However, using appendleft(), adding an element to the list’s beginning is much easier. See the example below:

deque1 = collections.deque([1,2,3,4,5])
deque1.appendleft(4)
print(deque1)

Output:

deque([4, 1, 2, 3, 4, 5])

extendleft() collection

Another deque operation is extendleft(), which permits to insert not only one but several items at the front of the list, with one operation and O(1) performance. See the example below:

deque1 = collections.deque([1,2,3,4,5])
deque1.extendleft([7,8,9])
print(deque1)

Output:

deque([9, 8, 7, 4, 1, 2, 3, 4, 5])

popleft() operation

And lastly, we will see the popleft() operation, which will remove the item at the top of the list. Again, it is convenient since it allows you to remove the first items without shifting all elements.

deque1 = collections.deque([1,2,3,4,5])

deque1.extendleft([7,8,9])
print(deque1)
deque1.popleft()
print(deque1)

Output:

deque([9, 8, 7, 1, 2, 3, 4, 5])
deque([8, 7, 1, 2, 3, 4, 5])

Conclusion

To summarize, we have seen how to use two python collections: namedtuple and deque. Namedtuple is useful when you won’t to create object on the fly without previously defining a class. Deque is handy in cases where to add or remove elements from both end of the list.

I hope this article was useful and thank you so much for reading and supporting this blog! Happy Coding!

More Interesting Articles

Project-Based Programming Introduction

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications

100% Recommended book for Java Beginners

Unique lay-out and teaching programming style helping new concepts stick in your memory

90 Specific Ways to Write Better Python

Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples

Grow Your Java skills as a developer

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Write Code as a Professional Developer

Excellent read for anyone who already know how to program and want to learn Best Practices

Every Developer should read this

Perfect book for anyone transitioning into the mid/mid-senior developer level

Great preparation for interviews

Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java