Series: Learning Python: A Comprehensive Beginner Level Tutorial Series 🚀

Python's collections Module:

Dive into Python's collections module. Our comprehensive guide explains collections data structures, their usage, and practical examples for effective data management in Python
E
Edtoks2:14 min read

The collections module in Python provides a variety of specialized container data types that are useful for different purposes. Here are some additional methods and functionality of the collections module along with examples:

1. namedtuple Factory Function:

collections.namedtuple(typename, field_names, [verbose=False, rename=False]): Creates a new named tuple subclass with named fields.

from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])

p = Point(1, 2)

print("Point:", p)

2. deque (Double-Ended Queue):

collections.deque([iterable[, maxlen]]): Creates a new deque object.

Provides efficient O(1) operations for adding and removing elements from both ends.

from collections import deque
d = deque([1, 2, 3])

d.append(4)

d.appendleft(0)

print("Deque:", d)

3. Counter (Counting Elements):

collections.Counter([iterable-or-mapping]): Creates a dictionary-like object for counting elements.

from collections import Counter
colors = ['red', 'blue', 'red', 'green', 'blue', 'red']

color_count = Counter(colors)

print("Color Count:", color_count)

4. defaultdict (Default Values):

 

collections.defaultdict([default_factory[, ...]]): Creates a dictionary with default values for missing keys.

from collections import defaultdict

d = defaultdict(int)
d['a'] += 1
print("Default Dict:", d['a'])

5. OrderedDict (Ordered Dictionary):

collections.OrderedDict([items]): Creates a dictionary that maintains the order of insertion.

from collections import OrderedDict
d = OrderedDict()

d['one'] = 1

d['two'] = 2

print("Ordered Dict:", d)

6. ChainMap (Combining Dictionaries):

 

collections.ChainMap(*maps): Combines multiple dictionaries into a single view.

from collections import ChainMap
dict1 = {'a': 1, 'b': 2}

dict2 = {'b': 3, 'c': 4}

combined_dict = ChainMap(dict1, dict2)

print("Combined Dict:", combined_dict['b'])

7. UserDict, UserList, and UserString:

These classes provide user-friendly wrapper classes for dictionaries, lists, and strings, respectively.

from collections import UserDict, UserList, UserString
class MyDict(UserDict):

pass
d = MyDict({"a": 1, "b": 2})

print("User Dictionary:", d)

These are some additional methods and functionality provided by the collections module in Python. They are valuable for solving various programming tasks efficiently using specialized data structures.