Skip to content

    collections Module

    Python · Intermediate

    Definition

    collections offers Counter, defaultdict, deque, namedtuple and OrderedDict for common patterns.

    Shortens DSA solutions dramatically.

    Diagram

    Counterdefaultdictdequenamedtuple

    Flowchart

    Counter to countdefaultdict to groupdeque for queuesnamedtuple for records

    Example: Group anagrams

    from collections import defaultdict
    g = defaultdict(list)
    for w in ['eat', 'tea', 'tan', 'nat']:
        g[''.join(sorted(w))].append(w)
    print(list(g.values()))

    Output: [['eat', 'tea'], ['tan', 'nat']]

    Key points

    • Counter supports + and − of counts
    • heapq pairs well for top-k

    Interview questions

    dict vs defaultdict?

    defaultdict creates a default value for missing keys instead of raising KeyError.

    More Python topics