๐ Collections Module
This module implements specialized container datatypes providing alternatives to Python's general purpose built-in containers.
Mastering this concept will significantly boost your Python data science skills!
๐ป Code Example:
from collections import ( Counter, defaultdict, deque, namedtuple, OrderedDict, ChainMap ) # 1. Counter โ frequency analysis pynfinity_tags = ["python", "ai", "python", "devops", "ai", "python", "testing", "ai"] tag_counts = Counter(pynfinity_tags) print("Tag counts:", tag_counts) print("Top 2:", tag_counts.most_common(2)) # Arithmetic on Counters weekly_a = Counter({"python": 30, "ai": 20}) weekly_b = Counter({"python": 10, "ai": 25, "devops": 15}) print("Combined:", weekly_a + weekly_b) # 2. defaultdict โ skip KeyError for missing keys course_students = defaultdict(list) enrollments = [("santoshtvk", "Python"), ("dhruv", "AI"), ("tvk", "Python"), ("alice", "AI"), ("tvk", "DevOps")] for user, course in enrollments: course_students[course].append(user) print("\nStudents per course:") for course, students in course_students.items(): print(f" {course}: {students}") # 3. deque โ efficient double-ended queue history = deque(maxlen=5) # Auto-drops oldest when full for url in ["/home", "/pebbles", "/compiler", "/courses", "/reaction", "/dsa"]: history.append(url) print("\nBrowse history (last 5):", list(history)) history.appendleft("/welcome") # Add to front history.rotate(1) # Rotate right print("After rotate:", list(history)) # 4. namedtuple โ lightweight immutable record Pebble = namedtuple("Pebble", ["id", "title", "author", "score"]) p1 = Pebble("abc123", "Python Decorators", "santoshtvk", 4.9) print(f"\nPebble: {p1.title} by {p1.author} โ โญ{p1.score}") print("As dict:", p1._asdict()) # 5. ChainMap โ layered configuration defaults = {"theme": "dark", "lang": "en", "timeout": 30} user_cfg = {"theme": "light", "lang": "hi"} config = ChainMap(user_cfg, defaults) print("\nEffective config:") for k, v in config.items(): print(f" {k}: {v}")
Keep exploring and happy coding! ๐ป