MyInternships.in

Python Advanced

Python collections Module

The collections module extends Python's basic data structures with specialized, high-performance alternatives like Counter, defaultdict, namedtuple, and deque.


Counter — Counting Items

Counter builds a dictionary-like object that counts how many times each item appears in a list or string, saving you from writing a manual counting loop.

Counting letters
Python
from collections import Counter

words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counts = Counter(words)

print(counts)
print(counts.most_common(2))

defaultdict — Dictionaries with Defaults

A normal dictionary raises a KeyError when you access a missing key. defaultdict automatically creates a default value (like an empty list) for any new key, which is great for grouping data.

Grouping items by category
Python
from collections import defaultdict

groups = defaultdict(list)
groups["fruits"].append("apple")
groups["fruits"].append("banana")
groups["veggies"].append("carrot")

print(dict(groups))

namedtuple — Readable Tuples

namedtuple creates a lightweight class-like tuple where you access fields by name instead of position, making code that returns structured data much easier to read.

A Point namedtuple
Python
from collections import namedtuple

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

print(p.x, p.y)

deque — Fast Double-Ended Queue

A regular list is slow when adding or removing items from the front. deque (pronounced "deck") is optimized for fast additions and removals from both ends, ideal for queues and sliding-window problems.

Using deque
Python
from collections import deque

queue = deque([1, 2, 3])
queue.appendleft(0)
queue.append(4)
print(queue)
queue.popleft()
print(queue)

OrderedDict — Insertion-Ordered Dictionaries

Since Python 3.7, regular dictionaries already remember insertion order, but OrderedDict still offers extra methods like move_to_end() and is useful when you need to signal ordering intent explicitly.

💡

For most modern code, a plain dict is enough since it preserves order — reach for OrderedDict only when you need its extra reordering methods.

TypeUse case
CounterCounting occurrences of items
defaultdictDictionaries with automatic default values
namedtupleLightweight objects with named fields
dequeFast append/pop from both ends
OrderedDictDictionary with explicit reordering methods

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships