Collections in Python – Quickstart

In Python, the collections module provides alternatives to Python’s built-in container types like dict, list, and tuple. These alternatives are often more flexible, efficient, or feature-rich than their basic counterparts. Some of the main classes and types provided by the collections module, along with their key properties.

ChainMap

ChainMap class is part of the collections module and allows us to group multiple dictionaries or mappings into a single view. ChainMap in short is called as collection of dictionaries. It is particularly useful when we want to search through multiple dictionaries as if they were a single dictionary.

Counter

Counter is used to count hashable objects. It store the objects as dictionary keys and their counts as values. Counter is like a dictionary which is used for counting items and is very useful for frequency analysis, counting occurrences of elements, words in a document, or any other type of collection.

deque

deque provides an optimized and efficient way to work with a queue and stack data structures. It allows insertion (append) and removal (pop) of elements from both ends (left and right) with O(1) time complexity. Since, deque supports appending and popping from both ends, it can be used as both Stacks (LIFO – Last In First Out) and Queues (FIFO – First In First Out).

namedtuple

namedtuple collection in Python, allows us to create classes which are immutable tuples but with named fields. This is a subclass of Python’s built-in tuple. Named fields make the tuple elements more readable because then we can access elements by names rather than indices.

defaultdict

In Python, defaultdict is a subclass of the built-in dict class. defaultdict returns a new dictionary-like object. It provides a default value for a nonexistent key automatically, without raising a KeyError. It is part of the collections module.

OrderedDict

An OrderedDict in Python is a dictionary class from the collections module. It is a subclass of the dict class. This is used to maintain the order of key-value pairs, in which keys are inserted to this dictionary.

UserDict, UserList and UserString

In Python UserDict, UserList and UserString are classes in the collections module. These classes provide a way to create custom dictionary, list, and string-like objects by inheriting from them. These classes are useful when we need to extend or modify the behavior of the built-in types like dictionaries, lists, and strings, but still have their basic structure and functionalities.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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