Day 5: Python's collections Module - When & Why to Use It? ??
Sarasa Jyothsna Kamireddi
Aspiring Python Developer | Machine Learning Enthusiast | Experienced in Reliability Engineering
Python's collections module provides specialized data structures with better performance and functionality than standard lists, tuples, and dictionaries. ??
Today, I'll explore some of the most useful collections classes and show you when and why to use them! ??
1?? Counter - Counting Made Easy
Used for counting hashable objects (like list elements or characters in a string)
from collections import Counter
words = ["apple", "banana", "apple", "orange", "banana", "banana"]
word_count = Counter(words)
print(word_count) # Couter({'banana': 3, 'apple': 2, 'orange': 1})
?? When to use?
?? Counting elements in a list or string
?? Finding the most common items
?? Quick frequency analysis
2?? defaultdict - Avoid Key Errors in Dictionaries
A defaultdict provides a default value when a key is missing, avoiding KeyError
? Example: Grouping Data
from collections import defaultdict
grouped_data = defaultdict(list)
data=[("fruit","apple"), ("fruit","banana"), ("vegetable","carrot")]
for category, item in data:
grouped_data[category].append(item)
print(grouped_data)
?? When to use?
?? Avoiding KeyError
?? Creating grouped dictionaries dynamically
?? Initializing missing keys with default values
3?? deque - Faster Lists for Insertions & Deletions
A deque (double-ended queue) allows fast appends and pops from both ends O(1) complexity
? Example: Efficient Queue Implementation
from collections import deque
queue = deque(["A", "B", "C"])
queue.append("D") # add to end
queue.appendleft("Z") # add to front
print(queue) # deque(['Z', 'A', 'B', 'C', 'D'])
queue.pop() # Remove from end
queue.popleft() # Remove from front
?? When to use?
?? Implementing queues or stacks efficiently
?? Handling large datasets with frequent insertions/removals
领英推荐
?? Faster that list.append() ad list.pop(0)
4?? namedtuple - Readable Tuples with Names
A namedtuple gives tuples named attributes, making them more readable than regular tuples
? Example: Creating a Named Tuple
from collections import namedtuple
Person = namedtuple("Person", ["name", "age"])
person1 = Person(name="Jyothsna", age=25)
print(person1.name) # Jyothsna
print(person1.age) # 25
?? When to use?
?? When we need lightweight objects without a full class
?? Making code more readable with named attributes
?? Storing database rows, coordinates, etc
5?? OrderedDict - Keep Dictionary Order (Before Python 3.7)
An OrderedDict remembers the insertion order of keys (useful in Python < 3.7, where normal dicts didn't maintain order)
? Example: Preserving Order
from collections import OrderedDict
ordered_dict = OrderedDict()
ordered_dict["b"] = 2
ordered_dict["a"] = 1
ordered_dict["c"] = 3
print(ordered_dict) # Maintains order of insertion
?? When to use?
?? When using Python before 3.7 (now, regular dict maintains order)
?? Keeping insertion order for specific applications
Summary of collections Module
?? Counter - Quick frequency counts
?? defaultdict - Avoid missing key errors
?? deque - Faster list operations
?? namedtuple - Readable tuples
?? OrderedDict - Maintains order
#100DaysOfCode #Python #Collections #Programming #Coding