Collections
Data structures with Increased functionality
The collections
module in Python provides specialized data structures that extend the built-in types like lists,
tuples, and dictionaries. These data structures offer enhanced functionality and efficiency.
Counter
A Counter
is a dictionary subclass used to count occurrences of elements.
from collections import Counter
# Example: Counting letters in a word
word = "mississippi"
counter = Counter(word)
print(counter)
Output:
{'i': 4, 's': 4, 'p': 2, 'm': 1}
Useful Methods:
.most_common(n)
: Returns then
most common elements..elements()
: Returns an iterator repeating each element as per count.
print(counter.most_common(2)) # [('i', 4), ('s', 4)]
defaultdict
A defaultdict
is a dictionary that assigns default values to keys that don’t exist.
from collections import defaultdict
# Default value type is list
students = defaultdict(list)
students["Math"].append("Jasmeet")
students["Science"].append("Chris")
print(students)
Output:
{'Math': ['Jasmeet'], 'Science': ['Chris']}
Why Use defaultdict
?
- Avoids
KeyError
- Automatically initializes missing keys
deque
A deque
(pronounced "deck") is a faster list optimized for insertion and deletion from both ends.
from collections import deque
queue = deque(["Jasmeet", "Chris", "Charlie"])
queue.append("David") # Add to the right
queue.appendleft("Eve") # Add to the left
print(queue)
Output:
deque(['Eve', 'Jasmeet', 'Chris', 'Charlie', 'David'])
Useful Methods:
.pop()
: Removes from the right.popleft()
: Removes from the left.extend(iterable)
: Extends from the right
namedtuple
A namedtuple
is an immutable tuple where elements have meaningful names.
from collections import namedtuple
# Define a named tuple
Person = namedtuple("Person", ["name", "age", "city"])
# Create an instance
p1 = Person(name="Jasmeet", age=25, city="New York")
print(p1.name, p1.age, p1.city)
Output:
Jasmeet 25 New York
Why Use namedtuple
?
- Improves code readability
- Memory-efficient
OrderedDict
An OrderedDict
remembers the order in which items were added (from Python 3.7+, regular dictionaries do this too).
from collections import OrderedDict
ordered_dict = OrderedDict()
ordered_dict["a"] = 1
ordered_dict["b"] = 2
ordered_dict["c"] = 3
print(ordered_dict)
Output:
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
Why Use OrderedDict
?
Useful when maintaining order is essential.
Why Use Collections Module?
✅ More efficient than built-in data types
✅ Provides advanced functionality
✅ Reduces code complexity