Python Tutorial 0/52 lessons ~6 min read Lesson 24

    collections Module

    collections Module in Data Structures: core concepts, worked examples, and practical guidance in one focused lesson.

    Course progress0%
    Focus
    8 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    collections ships production-grade containers: Counter, defaultdict, deque, OrderedDict, namedtuple. Use them instead of reinventing.

    Understanding the topic

    Core concepts to understand:

    • Counter — frequency map.
    • defaultdict — auto-init missing keys.
    • deque — O(1) prepend/append.
    • namedtuple — tuple with names.

    Syntax reference

    Visual flow / code:

    python
    from collections import Counter, defaultdict, deque
    # Counter
    Counter("mississippi").most_common(2)
    # [('i', 4), ('s', 4)]
    # defaultdict
    groups = defaultdict(list)
    for word in ["apple", "ant", "bee"]:
    groups[word[0]].append(word)
    # deque (efficient queue)
    q = deque(maxlen=3)
    q.append(1); q.append(2); q.appendleft(0)

    Execution workflow

    1collections Module Workflow
    1 / 4

    Counter

    frequency map.

    Real-world use

    Counter is the one-liner for word/event histograms. deque is the right structure for rolling windows and BFS queues.

    Best practices

    • Counter for histograms.
    • defaultdict for grouped data.
    • deque for FIFO/sliding windows.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1IntermediateQuestionWhen use deque vs list?+

    Answer

    Use deque when you add or remove from both ends frequently, such as queues, BFS, or sliding windows, since appends and pops at either end are O(1). A list is O(n) for operations at the front because items shift. Use a list when you need fast indexing or slicing, as deque indexing in the middle is O(n).
    2BeginnerQuestionWhat does Counter.most_common return?+

    Answer

    Counter.most_common(n) returns a list of (element, count) tuples sorted by count in descending order, limited to the top n if given. Without an argument it returns all elements. Items with equal counts appear in the order they were first encountered, because dict order is preserved.

    Follow-up

    What does Counter do when you add two counters?
    3BeginnerQuestiondefaultdict use case?+

    Answer

    Use defaultdict whenever you group or count by key and want a missing key to start with a default, such as defaultdict(list) for grouping items by category or defaultdict(int) for counting. It removes boilerplate checks for key existence. For counting specifically, Counter is usually even clearer.

    Summary

    In summary: collections = batteries. Use them — don't reinvent.

    Ready to mark this lesson complete?Track your journey across the entire course.