Python collections Module
Example
Use Counter and deque:
from collections import Counter, deque
c = Counter(["Emil", "Tobias", "Emil"])
print(c["Emil"])
d = deque([1, 2])
d.appendleft(0)
print(list(d))
Try it Yourself »
Definition and Usage
The collections module provides specialized container datatypes.
Use it for efficient alternatives to built-in containers, like named tuples, counters, default dicts, deques, and ordered dicts.
Members
Member | Description |
---|---|
ChainMap | Class for creating a single view of multiple mappings. |
Counter | Dict subclass for counting hashable objects. |
Counter.elements() | Iterate over elements repeating each as many times as its count. |
Counter.most_common() | Return a list of the n most common elements and their counts. |
Counter.subtract() | Subtract counts from another Counter or iterable/mapping (allow negatives). |
Counter.total() | Return the total of all counts (sum of values). |
Counter.update() | Update counts from an iterable or mapping (add like a multiset). |
defaultdict | Dict subclass that calls a factory function to supply missing values. |
deque | List-like container with fast appends and pops on either end. |
namedtuple() | Create tuple subclasses with named fields. |
OrderedDict | Dict subclass that remembers insertion order (Py3.7+ dict preserves order by default). |
UserDict | Wrapper around dictionary objects for easier subclassing. |
UserList | Wrapper around list objects for easier subclassing. |
UserString | Wrapper around string objects for easier subclassing. |