Introduction
In this post, we’ll explore Python’s collections module. This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers.
Deque
Deque, pronounced as ‚deck‘, is an optimized list to perform insertion and deletion easily.
from collections import dequed = deque()d.append('a')d.append('b')print(d)# Output: deque(['a', 'b'])
Counter
Counter is a dict subclass for counting hashable objects.
from collections import Counterc = Counter('python')print(c)# Output: Counter({'p': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1, 'n': 1})
OrderedDict
OrderedDict is a dict subclass that remembers the order entries were added.
from collections import OrderedDictod = OrderedDict()od['a'] = 1od['b'] = 2print(od)# Output: OrderedDict([('a', 1), ('b', 2)])
DefaultDict
DefaultDict is a dict subclass that calls a factory function to supply missing values.
from collections import defaultdictdd = defaultdict(int)dd['a'] = 1dd['b'] = 2print(dd)# Output: defaultdict(, {'a': 1, 'b': 2})
NamedTuple
NamedTuple is a function for creating tuple subclasses with named fields.
from collections import namedtuplePoint = namedtuple('Point', ['x', 'y'])p = Point(11, y=22)print(p)# Output: Point(x=11, y=22)
These data structures can help you write more efficient and cleaner code. Let’s dive in!