Nearby lessons
135 of 159Python - 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
defaultdict
deque
namedtuple
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
Counterfor frequencies. - Use
defaultdictfor automatic grouped values. - Use
dequefor queues and both-end operations. - Use
namedtuplefor 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 QuestionsProgress: 0 / 8