Py Collections Module — Free Python Tutorial

Learn Py Collections Module in Python with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.

Py Collections Module — Free Python Tutorial

Learn Py Collections Module in Python with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.

✓ 100% Free ✓ No Login Needed ✓ NCERT / CBSE Aligned ✓ Download as PDF

TL;DR: Learn Py Collections Module in Python with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.

Written & reviewed by the Syllab.in Academic Team (CBSE/NCERT subject experts) · Updated

🤖 Stuck on any question? Ask Syllab's free AI Tutor for a step-by-step explanation — instant, unlimited, no login.

Py Collections Module in Python

The collections module provides specialised container types that extend Python's built-in dict, list, and tuple for common patterns — more efficient and expressive than implementing them yourself.

Counter(iterable) counts hashable elements and stores them as {element: count}. It supports arithmetic (+, -, &, |) and most_common(n) returns the n highest-count elements.

defaultdict(default_factory) is a dict that never raises KeyError — it calls default_factory() to create a missing value on first access. Common factories: list, set, int (for counting without Counter).

deque (double-ended queue) supports O(1) append/pop from BOTH ends, unlike list which is O(n) for left-side operations. Use maxlen for a sliding window or fixed-size history buffer.

Other highlights: OrderedDict (remembers insertion order — mostly superseded by dict in Python 3.7+), namedtuple (lightweight class-like tuple with field names), ChainMap (logical merge of multiple dicts).

Py Collections Module — Syntax

from collections import Counter, defaultdict, deque, namedtuple

Counter("banana")            # Counter({'a':3,'n':2,'b':1})
Counter.most_common(2)       # [('a',3),('n',2)]

dd = defaultdict(list)
dd["key"].append(1)          # no KeyError

dq = deque([1,2,3], maxlen=3)
dq.appendleft(0)             # O(1)! deque → [0,1,2]

Point = namedtuple("Point", ["x","y"])

Learn Py Collections Module step by step with Syllab's free interactive Python tutorial — runnable code examples, practice exercises and instant AI feedback, all free with no signup. Explore the full Python course →