Python Collections — The In-Depth Guide To Those Special Data Structures
We are all familiar with the fundamental data structures in Python — the list, dictionary, tuple and set. Some of us may even be quite…
We are all familiar with the fundamental data structures in Python — the list, dictionary, tuple and set. Some of us may even be quite well versed in it. In this article, we’ll go into learning some of the special ones, those which are based on, or derived from these basic data structures. If you already know them, this might be a good recall for you as well.

Let’s get right into it!
Python has the collections module which has all these data structures for us to use in our daily tasks. They come in handy in a variety of ways, and if you’re a competitive programmer or a data scientist or a machine learning engineer, you should be familiar with at least a few of these classes for day to day usage.
For those of you who want to get ahead and read this article along with the official documentation — here you go.
There are nine specialised ‘containers’, as they call it, in the collections module. They include:
deque
OrderedDict
namedtuple()
Counter
ChainMap
defaultdict
UserString
UserList, and finally,
UserDict
Going ahead and importing the module with:
from collections import *
Let us look into their functionalities one by one!
The deque container — working with queues and stacks in one!
Compared to the normal lists, deque offers functions to append(insert item) and remove(delete item) from both sides of the list. It is normally regarded as a doubly ended queue for the same.
Major functions as we can gather from the example, work in a similar way as lists do. Time complexity for append and pop operations are, however, optimised to O(1) instead of the O(n) in lists.
The special functions in deque can be demonstrated with the following snippet:
As it must be clear, we can pop the item in a First In First Out order, like we do in a queue as well. Well, this is new!
The OrderedDict container — for preserving our order of insertion!
This one is basically a subclass of our good old dictionary class, but what’s better is that it provides us with the functionality to preserve the order in which we insert our elements into the dictionary.
Let’s get better at understanding it with an example.
This must give you an idea of what we were talking about before. What’s even better is that it OrderedDict retains all the functions of dict as well!
But that’s not it, we have a special function too in here, of course.
popitem
(last=True)
This function is the one that gives us the power to remove an element in either of two ways:
FIFO manner — by setting last = False
LIFO manner — keeping last as True.
So this happens:
the namedtuple() class — for providing custom names for our tuples!
As the official documentation describes it:
The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable.
So essentially, namedtuple class can be used to return a tuple object with names for each position.
This is the basic concept to understand here — we can have a name associated with each tuple, rest of the functionality for the tuple is the same.
Another special function to take note of here is the _make(list) function. This one returns a list as our namedtuple. Like this:
The Counter class — for speedy item counting!
For getting a count of every element in a dictionary or a list, we can have the Counter class to do it for us!
As you can see, it returns the count of elements as a dictionary.
That is it for our Counter class! Go ahead and save at least ten lines of code through this class (and a for loop for counting elements that you won’t need now) :)
ChainMap container — to store a collection of dictionaries as one!
The main functionality is essentially this — it encapsulates many dictionaries into a single unit and returns a list of dictionaries. Look at this example:
It really is as simple as that! And it can still be called in the same manner as our normal dictionaries. Adding another dictionary is also very simple, just use the new_child function!
The defaultdict class — a default, error-free dictionary at our disposal!
It is a subclass of dict class and returns a new dictionary-like object, and for the keys not present in the dictionary, it provides some default value so as to never raise a KeyError, as you can see from the example.
It really is the simplest one to understand in our whole collections module.
Custom containers with UserDict, UserList and UserString!
These three classes essentially allow you to use the built in dictionaries, lists or strings and infuse them with any custom functions, as you’d like according to your use case. UserList acts as a wrapper around list objects, UserDict around dict objects and UserString around the string objects.
Let us look at an example. Here, we define a custom list with UserList in which we add a new method of our own to make and return a dictionary with alternate elements from the list.
Here is what I’m talking about:
Ha! We’ve successfully added a custom feature to our lists!
The implementation of UserDict and UserString is quite similar, so now that you have the idea, please go ahead and play with them on your own. :)
Here is the complete code from my GitHub repository for your reference:
yashprakash13/Python-Collections-Playground
You can't perform that action at this time. You signed in with another tab or window. You signed out in another tab or…github.com
Thank you for reading and I hope you find this article helpful! ❤ Subscribe to This Code to get the chance to read similar stories like this in the future as well! :)