There are some built-in data types in Python, such as int, str, list, tuple, dict, etc. Python’s collections module builds on these built-in data types by providing several additional data types.
|namedtuple()||generates a subclass of tuple that can use the name to access the content of the element|
|deque||A list-like container that implements fast append and pop at both ends|
|Counter||A subclass of dictionary that provides counting of hashable objects|
|OrderedDict||subclass of dictionaries that preserve the order in which they are added|
|defaultdict||A subclass of dictionary that provides a factory function to provide a default value for dictionary queries|
|UserDict||wraps dictionary objects, simplifying dictionary subclassing|
|UserList||wraps a list object, simplifying list subclassing|
|UserString||encapsulates the list object, simplifying string subclassing|
namedtuple is used to generate data objects that can be accessed by name, and is often used to enhance the readability of the code, especially when accessing data of type namedtuple.
deque is actually an abbreviation for double-ended queue, which translates to double-ended queue, and its biggest benefit is that it enables to add and remove objects from the head of the queue quickly: .popleft(), .appendleft().
You may say, the native list can also add and remove objects from the head, right? Like this.
However, it is worth noting that the time complexity of these two uses of the list object is O(n), which means that the time taken increases linearly with the number of elements. As a double-ended queue, deque also provides some other useful methods, such as rotate, etc.
Counter is a simple counter that counts, for example, the number of occurrences of a character.
An ordered dictionary is like a regular dictionary, but with some extra features related to sorting operations. As the built-in dict class gains the ability to remember the order of insertion (a new behavior guaranteed in Python 3.7), it becomes less important.
We all know that when using Python’s native data structure dict, if you access it with something like d[key], a KeyError exception will be thrown when the specified key doesn’t exist. However, with defaultdict, if you pass in a default factory method, then when you request a non-existent key, the factory method will be called and the result will be used as the default value for the key.