Tutorial

How To Use the collections Module in Python 3

Practical guide to the python collections module: how to use namedtuple, defaultdict, and deque with examples and when to choose each.

Drake Nguyen

Founder · System Architect

3 min read
How To Use the collections Module in Python 3
How To Use the collections Module in Python 3

Introduction

The python collections module offers higher-level container datatypes beyond the built-in list, dict, and tuple. In Python 3, this part of the standard library provides utilities that make common tasks—like adding named fields to tuples, grouping values in a dictionary, and adding or removing items from either end of a sequence—both clearer and more efficient. This tutorial shows how to use three frequently used classes from the collections module: namedtuple, defaultdict, and deque, using small, practical examples.

Prerequisites

  • Basic familiarity with Python tuples, lists, and dictionaries (syntax and indexing).
  • Python 3 installed (examples use Python 3 syntax).
  • Comfort reading short code snippets—each example is self-contained and annotated.

Adding named fields to tuples with namedtuple

Tuples are ordered and immutable, but positional fields can be unclear when reading code. collections.namedtuple creates a lightweight class that behaves like a tuple while giving each position a descriptive name. This makes code easier to read and maintain—an excellent technique for data structures with fixed fields.

# python namedtuple example with fields
from collections import namedtuple

Fish = namedtuple('Fish', ['name', 'species', 'tank'])
sammy = Fish('Sammy', 'shark', 'tank-a')

print(sammy)            # Fish(name='Sammy', species='shark', tank='tank-a')
print(sammy.species)    # Access by name
print(sammy[1])         # Access by index (tuple-like)

namedtuple instances expose helpful methods too, such as _asdict() (which returns a mapping of field names to values) and _replace() (that returns a new instance with one or more fields changed). Use namedtuple when you want immutability and readable, named fields—common in many python collections module examples.

Collecting and grouping data with defaultdict

defaultdict supplies a default value for missing keys to avoid KeyError and reduce boilerplate. A common pattern is grouping items by a key—for example, grouping fish names by their tank. The factory function you pass to defaultdict determines the default container (list, set, int, etc.).

# python defaultdict vs dict example: grouping values in dictionary using defaultdict
from collections import defaultdict

fish_inventory = [
    ('Sammy', 'shark', 'tank-a'),
    ('Jamie', 'cuttlefish', 'tank-b'),
    ('Mary', 'squid', 'tank-a'),
]

fish_by_tank = defaultdict(list)
for name, species, tank in fish_inventory:
    fish_by_tank[tank].append(name)

print(fish_by_tank)  # defaultdict(, {'tank-a': ['Sammy', 'Mary'], 'tank-b': ['Jamie']})

Compared to a plain dict, defaultdict eliminates the need to check for a key and initialize an empty list before appending. This idiom appears in many python collections module tutorials and is especially useful for grouping or counting tasks (use int as the factory for simple counters).

Efficiently adding and removing from either end with deque

The deque (double-ended queue) is a list-like container optimized for fast appends and pops from both ends. For operations that require frequent insertions or removals at the beginning of a sequence, deque typically performs better than list in terms of big O time complexity.

# python deque appendleft popleft examples
from collections import deque

favorites = deque(['Sammy', 'Jamie', 'Mary'])

favorites.appendleft('Alice')   # O(1) — insert at left
print(favorites)                # deque(['Alice', 'Sammy', 'Jamie', 'Mary'])

first = favorites.popleft()     # O(1) — remove from left
print(first, favorites)         # 'Alice', deque(['Sammy', 'Jamie', 'Mary'])

Keep in mind deque does not make random access faster—indexing into a deque is O(n), whereas list indexing is O(1). Choose deque when you need efficient additions/removals on both ends (when to use deque vs list python), and use list when you need fast random access.

Putting it together: quick reference

  • namedtuple: readable, immutable records—use for fixed-field data structures (python namedtuple example with fields).
  • defaultdict: compact grouping and counting without KeyError—excellent for grouping values in dictionary using defaultdict python patterns.
  • deque: constant-time appends and pops on either end—perfect for queues, sliding windows, and other double-ended operations.

Conclusion

The python collections module provides practical, well-tested data structures that simplify common programming tasks. Whether you’re following a python collections module tutorial, experimenting with collections python3 examples, or deciding between defaultdict and a regular dict, these tools help write clearer and more efficient code. Explore the module documentation and try these patterns in small scripts to internalize when to prefer namedtuple, defaultdict, or deque.

Tip: combine these building blocks—use namedtuple for record-like entries, defaultdict to aggregate them, and deque when you need efficient end-based operations.

Stay updated with Netalith

Get coding resources, product updates, and special offers directly in your inbox.