πŸ“š Python Tutorial β€” Collections Module

Introduction 🌟

The collections module provides high-performance, feature-rich alternatives to Python’s built-in data types. These specialized container datatypes improve readability, efficiency, and functionality for real-world applications.

Note

πŸ’‘ Key components: namedtuple, deque, Counter,defaultdict, OrderedDict, ChainMap

1. namedtuple β€” Lightweight Object Replacement 🧱

namedtuple creates tuples with named fields. It behaves like a class but is immutable and lightweight.

namedtuple_example.py

from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)

print(p.x, p.y)
print(p)
  • βœ” Access by name (p.x)
  • βœ” Memory efficient
  • βœ” Immutable like normal tuples

2. deque β€” Fast Queue/Stack Implementation πŸ”

deque is ideal for append/pop operations from both ends. Faster than lists for queue/stack usage.

deque_example.py

from collections import deque

dq = deque([1, 2, 3])
dq.append(4)
dq.appendleft(0)

print(dq)

dq.pop()
dq.popleft()

print(dq)
  • βœ” append() & appendleft()
  • βœ” pop() & popleft()
  • βœ” Efficient O(1) operations

3. Counter β€” Count Items Easily πŸ”’

Counter counts the occurrence of elements in an iterable.

counter_example.py

from collections import Counter

counts = Counter("banana")
print(counts)
print(counts["a"])
print(counts.most_common(2))
  • βœ” Frequency counting
  • βœ” Analyze text, logs, inventory
  • βœ” Supports arithmetic operations between counters

4. defaultdict β€” Default Values for Missing Keys πŸ”‘

defaultdict automatically assigns a default value when a missing key is accessed.

defaultdict_example.py

from collections import defaultdict

dd = defaultdict(int)
dd["a"] += 1

dd_list = defaultdict(list)
dd_list["users"].append("Sathish")

print(dd)
print(dd_list)
  • βœ” Avoids KeyError
  • βœ” Perfect for grouping, counting

5. OrderedDict β€” Keeps Insertion Order πŸ“Œ

Python 3.7+ dictionaries preserve insertion order by default, but OrderedDict offers extra methods like move_to_end().

ordereddict_example.py

from collections import OrderedDict

od = OrderedDict()
od["a"] = 1
od["b"] = 2
od["c"] = 3

od.move_to_end("b")
print(od)
  • βœ” Useful for LRU caches
  • βœ” Provides reordering features

6. ChainMap β€” Combine Multiple Dictionaries πŸ”—

ChainMap groups multiple dictionaries into a single view.

chainmap_example.py

from collections import ChainMap

defaults = {"theme": "dark", "language": "en"}
user_settings = {"language": "ta"}

config = ChainMap(user_settings, defaults)
print(config["theme"])
print(config["language"])
  • βœ” Dictionary layering
  • βœ” Useful for configuration files

7. UserDict, UserList, UserString β€” Custom Mutable Classes πŸ› οΈ

These classes allow you to create custom versions of built-in types with extended behaviors.

userdata_example.py

from collections import UserDict

class MyDict(UserDict):
    def popitem(self):
        print("Pop called")
        return super().popitem()

d = MyDict({"a": 1, "b": 2})
d.popitem()
  • βœ” Extend dict, list, or string safely
  • βœ” Useful for validation, custom behavior

8. Complete Real-World Example β€” Word Frequency Counter πŸ“Š

word_frequency.py

from collections import Counter

text = "apple banana apple orange banana apple"
words = text.split()

freq = Counter(words)
print(freq)
print(freq.most_common(1))

βœ” Best for text analysis & NLP tasks

9. Real-World Example β€” Queue System Using deque 🚌

queue_example.py

from collections import deque

queue = deque()

queue.append("User1")
queue.append("User2")
queue.append("User3")

print("Serving:", queue.popleft())
print("Now:", queue)

10. Collections Module Cheat Sheet πŸ“˜

ClassDescription
namedtupleLightweight object alternative
dequeFast queue/stack
CounterCounts elements
defaultdictDefault values for missing keys
OrderedDictOrdered dictionary with extra features
ChainMapCombine dictionaries
UserDictCustom dictionary behavior
UserListCustom list behavior
UserStringCustom string behavior

Best Practices πŸ’‘

  • βœ” Use Counter for counting frequencies
  • βœ” Use deque instead of list for queues
  • βœ” Use defaultdict when grouping items
  • βœ” Use namedtuple for clean, immutable objects
  • βœ” Use ChainMap for layered configurations

Conclusion πŸŽ‰

>>β€œThe collections module upgrades Python's built-in types β€” giving you powerful and elegant tools for real-world data handling.” ✨

You now fully understand the Collections Module! Want the next topic? Try itertools, functools, statistics, or pathlib. Just tell me! 😊