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 Tuple, List, Dictionary, etc.
namedtuple():-
The Python namedtuple() function returns a tuple-like object with names for each position in the tuple. It was used to eliminate the problem of remembering the index of each field of a tuple object in ordinary tuples.
Example:-
Output:-
OrderedDict():-
The Python OrderedDict() is similar to a dictionary object where keys maintain the order of insertion. If we try to insert key again, the previous value will be overwritten for that key.
Example:-
Output:-
defaultdict():-
The Python defaultdict() is defined as a dictionary-like object. It is a subclass of the built-in dict class. It provides all methods provided by the dictionary but takes the first argument as a default data type.
Example:-
Output:-
Counter():-
The Python Counter is a subclass of dictionary object which helps to count hashable objects.
Example:-
Output:-
deque():-
The Python deque() is a double-ended queue which allows us to add and remove elements from both ends.
Example:-
Output:-
ChainMap:-
A chainmap class is used to group multiple dictionaries together to create a single list. The linked dictionary stores in the list and it is public and can be accessed by the map attribute.
Example:-
Output:-
This is all about the Collection module in Python.
Comments