1 year

The collections module

The collection Module in Python provides different types of containers. A Container is an object that is used to store different objects and provide a way to access the contained objects and iterate over them. Some of the built-in containers are TupleListDictionary, etc. In this article, we will discuss the different containers provided by the collections module.

Data type Description
namedtuple() Factory function for creating tuple subclasses with named fields
deque List-like container with fast appends and pops on either end
ChainMap Dictionary-like class for creating a single view of multiple mappings
Counter Dictionary subclass for counting hashable objects
OrderedDict Dictionary subclass that remembers the order entries were added
defaultdict Dictionary subclass that calls a factory function to supply missing values
UserDict Wrapper around dictionary objects for easier dictionary subclassing
UserList Wrapper around list objects for easier list subclassing
UserString Wrapper around string objects for easier string subclassing



A namedtuple is a tuple-like object that has fields accessible by attribute lookup as well as being indexable and iterable (it's actually a subclass of tuple). This is sort of a compromise between a full-fledged object and a tuple, and it can be useful in those cases where you don't need the full power of a custom object, but you want your code to be more readable by avoiding weird indexing. Another use case is when there is a chance that items in the tuple need to change their position after refactoring, forcing the coder to refactor also all the logic involved, which can be very tricky.