Nearby lessons

135 of 159

Python - collections Module

📌 What You Will Learn
  • Import useful types from collections
  • Count values with Counter
  • Group or initialize values with defaultdict
  • Use deque for efficient double-ended queues
  • Create lightweight record types with namedtuple

Why collections exists

Lists and dictionaries are flexible general-purpose tools. The collections module adds containers for frequent counting, grouping, queue, and record patterns.

Counter

Loading editor…

defaultdict

Loading editor…

deque

Loading editor…

namedtuple

Loading editor…

OrderedDict and modern dictionaries

OrderedDict remains available for specialized ordering operations. Since Python 3.7, normal dictionaries preserve insertion order as a language guarantee, so use OrderedDict only when its extra methods or compatibility are useful.

Choosing a container

  • Use Counter for frequencies.
  • Use defaultdict for automatic grouped values.
  • Use deque for queues and both-end operations.
  • Use namedtuple for small immutable, named records.

Import styles

You can import the module as import collections or import a selected type such as from collections import Counter. Explicit imports make examples concise.

📝 Key Takeaways
  • collections provides specialized containers built on common patterns
  • Counter counts hashable values
  • defaultdict supplies a value for missing keys
  • deque supports efficient append and removal at both ends
  • Use the simplest built-in container that communicates intent

🧠 Test Your Knowledge

8 Questions
Progress: 0 / 8

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.