Collections Module In Python

Ankush kunwar
2 min readJan 11, 2023

--

Collections in Python are containers used for storing data and are commonly known as data structures, such as lists, tuples, arrays, dictionaries, etc. Python has a built-in collections module providing additional data structures for collections of data.

Here is a list of some of the classes provided by the collections module:

Counter: A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is often used to count the occurrences of items in a list or to compute the most common items in a list.

from collections import Counter

# Count the number of occurrences of each word in a list
words = ['red', 'blue', 'red', 'green', 'blue', 'blue']
counter = Counter(words)
print(counter) # Output: Counter({'blue': 3, 'red': 2, 'green': 1})

# Find the 3 most common words
print(counter.most_common(3)) # Output: [('blue', 3), ('red', 2), ('green', 1)]

OrderedDict: An OrderedDict is a dictionary subclass that remembers the order that keys were added. It is a dictionary that maintains the order of the keys as they are inserted.

from collections import OrderedDict

# Create an ordered dictionary
d = OrderedDict()
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['d'] = 4

# Iterate over the keys and values in the order they were added
for key, value in d.items():
print(key, value)

# Output:
# a 1
# b 2
# c 3
# d 4

defaultdict: A defaultdict is a subclass of the built-in dict class. It overrides one method to provide a default value for a dictionary key that does not exist.

from collections import defaultdict

# Create a defaultdict with a default value of 0
d = defaultdict(int)

# Try to access a key that doesn't exist
print(d['a']) # Output: 0

# Set the value of a key
d['a'] = 1
print(d['a']) # Output: 1

deque: A deque (double-ended queue) is a thread-safe, memory-efficient, and fast implementation of a queue that can be used as a stack (last-in, first-out data structure). It is a list-like object that allows fast appends and pops from either end.

from collections import deque

# Create a deque
d = deque()

# Add elements to the right of the deque
d.append(1)
d.append(2)
d.append(3)
print(d) # Output: deque([1, 2, 3])

# Add elements to the left of the deque
d.appendleft(0)
d.appendleft(-1)
print(d) # Output: deque([-1, 0, 1, 2, 3])

# Pop elements from the right of the deque
print(d.pop()) # Output: 3

# Pop elements from the left of the deque
print(d.popleft()) # Output: -1

Thank you for reading !!!

If you enjoy this article and would like to Buy Me a Coffee, please click here.

you can connect with me on Linkedin.

--

--