Collections in python – named tuple, deque, counter

Python collections are a module in the Python Standard Library, containing extra features and data types that you can use to your advantage.

In this article, I plan to touch the 3 most common and usable ones, but I encourage you to research more.

namedtuple

namedtuple is an easy way to represent a small simple class with no methods, it gives code readability, makes debugging easier, and saves classes on every tiny little object.

namedtuple IMO is one of the most underused objects in the collections module.
As always, an example is needed:

Always remember! readability counts, and the fact the function address p1,p2 attributes by name and not by location like a standard tuple, makes it more readable and understood by any developer who will read your code afterward, or even you if you haven’t touched it in a while

deque

another underused and powerful data type, the deque is like a “list with benefits”.
I’m sure you’re all working with lists all the time, but one of the lists most powerful features, are the order, and the pop & append.
pop and append in a list is O(1), but only the standard pop & append.

lists are great for LIFO (last in first out) but really bad for FIFO (first in first out), poping location n from a list or inserting to a specific location is O(n)!

This is where deque comes in handy, you can pop and insert from both sides in O(1), and can even rotate in an easy way — keeping the order but changing the starting point.

Example:

Counter

The counter is a simple and effective object, that counts!

While doing so, giving you great speed and comfort, and great features that can save you quite a few lines of code.

It takes an input of strings, lists, anything you want, and count repetitions inside, all in just one line of code, and gives you easy access in a dictionary-style object.

I hope you didn’t get tired of my examples:

We can see here, I’ve counted words, letters, and numbers, with only one line of code! this is a very strong tool that each python developer should know!

Leave a Reply

Your email address will not be published. Required fields are marked *

©pythoncoders