What useful types does the collections module provide?
What useful types does the collections module provide?
The collections module provides specialized container types that extend the built-in list/dict/tuple with convenient, often more efficient alternatives for common patterns. Knowing them lets you write cleaner, faster code.
from collections import defaultdict
# ❌ without it — must check/initialize keys manually
groups = {}
for item in items:
if item.category not in groups:
groups[item.category] = []
groups[item.category].append(item)
# ✅ defaultdict auto-creates the default for missing keys
groups = defaultdict(list) # missing key → a new empty list
for item in items:
groups[item.category].append(item) # no existence check needed
defaultdict(list) (or int, set, etc.) supplies a default for any missing key — eliminating the tedious check-and-initialize pattern. Great for grouping and counting.
from collections import Counter
c = Counter("mississippi") # Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})
c.most_common(2) # [('i', 4), ('s', 4)] — top 2
c["x"] # 0 — missing keys return 0, no error
Counter(["a", "b", "a", "c", "a"]) # count list items → {'a': 3, 'b': 1, 'c': 1}
Counter makes tallying frequencies trivial — counting words, votes, occurrences — with handy methods like most_common.
from collections import deque
q = deque([1, 2, 3])
q.append(4) # add to the right
q.appendleft(0) # add to the LEFT — O(1) (a list's insert(0) is O(n)!)
q.popleft() # remove from the left — O(1)
q = deque(maxlen=3) # bounded — auto-drops old items (sliding window)
deque is a double-ended queue with O(1) appends/pops at both ends — ideal for queues, stacks, and sliding windows (a plain list is O(n) for front operations).
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
p.x, p.y # 3, 4 — access by NAME (clearer than p[0], p[1])
p # Point(x=3, y=4) — readable
namedtuple gives tuples named fields — more readable than index access, immutable, memory-efficient. (Modern code often uses @dataclass instead for mutable records.)
OrderedDict → ordered dict (less needed since regular dicts keep order in 3.7+)
ChainMap → search multiple dicts as one (e.g. layered config/defaults)
Modulu collections yana ba abin da ya dace don alamsun da aka taƙi, yana bugi ga lambar da ta fi tsada da ƙoƙari sau da yawa. defaultdict da Counter suna sauƙe haɗa da kirgaje a sakamako (suna cire ilimin da aka yi da hannu); deque yana ba aiki na O(1) da mai tsaye-tsaye inda jiyye za ta kashe; namedtuple yana sanya jerin bayanan mara nauyi da za a iya karantawa.
Yawo ga waɗannan maimakon saida lambar da aka yi da hannu tare da jiyye dicts/lists shine alamar aiki mababbaki, sannu Python — ana samu su da yawa a lambar aiki ga sarrafa bayani, hanyoyi, da aiki mababbaki.
Ɗakin karatu na tambayoyin hira na IT tare da amsoshi cikakke — daga Junior zuwa Senior.
Ba da Gudummawa