Skip to main content
Module 8 · Lesson 3 of 431/36 in the course~16 min
Module lessons (3/4)

collections: Counter and defaultdict

Lesson preview5 hands-on exercises readyPython Course · Module 8 — Essential standard library

Counter for frequency counts, defaultdict for auto-initialized dicts, and namedtuple lightweight records.

What you'll learn in this lesson

  • Count frequencies of any iterable in a single line with Counter and .most_common().
  • Eliminate boilerplate if key not in d: in groupings using defaultdict(factory).
  • Model compact immutable records with namedtuple and access by field name.
  • Avoid the silent side effect of accessing a non-existent key in a defaultdict.

Overview

The built-in containers (list, dict, tuple, set) cover 90% of your needs, but as soon as you have to count occurrences, group elements by key or return lightweight records you find yourself always repeating the same if key not in d:. The collections module encapsulates exactly these recurring patterns in optimized C.

Compare the intent of each container: Counter accumulates frequencies, defaultdict automatically initializes new independent containers at the first key seen, and namedtuple gives readable names to the fields of a tuple without burdening memory.

Sections covered in this lesson

  1. 11. Instant counting with Counter
  2. 22. Automatic grouping with defaultdict
  3. 33. Independent containers vs shared references
  4. 44. Lightweight and immutable records with namedtuple
  5. 5Check for understanding
  6. 6Test yourself
Pro Lesson · Module 8 — Essential standard library

Unlock "collections: Counter and defaultdict" and the full Python Course curriculum

Counter for frequency counts, defaultdict for auto-initialized dicts, and namedtuple lightweight records.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Python Course plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.