Detailed explanation of Python collections module
When I first learned Python, I seemed to use the built-indict、list、tupleThat's enough.
But once you start writing more complex logic - such as the need for efficient double-ended insertion, elegant handling of missing keys, and detailed frequency statistics - the native container is a bit stretched: either the performance lags behind, or the code is filled with null and void logic.
At this time in the standard librarycollectionsModules are the perfect rescue solution.
It has built-in 7+ collection classes optimized for specific scenarios. It is seamlessly compatible with native containers and provides a large number of advanced functions out of the box.
Let’s break down the most core and most frequent tools.
1. namedtuple: immutable tuple with name
Ordinary tuples have a flaw: the elements are all accessed through index. If you look at the code two weeks later, you will probably not be able to remember whether index 0 is the x coordinate or the number.
namedtupleis specifically designed to save readability: it istupleA subclass of Tuple, each field has an attribute name, while retaining all the advantages of tuples such as immutability and memory efficiency.
Basic usage
Core Features
- Fully compatible with tuples: supports indexing, slicing,
len()、in、forLoops and other tuple operations - Extremely memory efficient: almost the same as ordinary tuples, faster and more memory-saving than custom lightweight classes
- Immutable: field value cannot be modified
Advanced Tips
2. deque: Double-ended queue (the optimal solution for queue/stack)
listAlthough queues can also be simulated (insert(0)、append()) or stack (append()、pop()), but the complexity of inserting/deleting from the head is O(n)**, and it will become significantly slower when there are more elements.
deque(double-ended queue) is specially designed for fast operation on both ends: left and rightappend / popBoth are O(1) and thread-safe.
Basic usage
Core Features
- O(1) on both ends: the first choice for queue/stack instead of list
- Thread Safety: You can operate with peace of mind in a multi-threaded environment
- Settingable maximum length: When maxlen is exceeded, the earliest added element will be automatically extruded
Advanced Tips
3. defaultdict: Dictionary with built-in guarantee
Use nativedictWhen accessing a non-existent key, the most annoying thing is to directly throwKeyError. For example, to count word frequency, you have to write:
defaultdictIt is here to solve this pain point.
it isdictA subclass of , you need to pass in a default value factory function when initializing - when accessing a non-existent key, this factory will be automatically called to generate a default value and fill in the dictionary.
Basic usage
Core Features
- Eliminate KeyError: Save a bunch of
if-elseDetermination code - Fully compatible with dict:
keys()、values()、items()Use as usual - Factory functions are very flexible: any callable object without parameters will do, such as
int、list、set, or even functions written by yourself
Advanced Tips
4. Counter: Dictionary designed for counting
Although statistical frequency can be useddefaultdict(int)realized, butCounterArmed to the teeth with this scene: built-inmost_common(), multi-set mathematical operations and other exclusive functions, making the code shorter and more semantic.
Basic usage
Core exclusive functions
5. OrderedDict: A dictionary with more controllable order
Starting with Python 3.7, plaindictIt has been officially guaranteed to maintain the insertion order of keys. ThatOrderedDictWhat other sense of existence is there?
It mainly has two commondictUnique skills that cannot be done:
- Flexible sequential operations, such as
move_to_end()Move the specified key to the beginning or end - Order-sensitive equality judgment: Only when the order and value of the key are the same are they considered equal.
Commonly used exclusive functions
6. Other utility classes
UserDict / UserList / UserString
These are wrapper classes for containers and do not directly inherit from the built-indict、list、str, but the usage is almost exactly the same.
Why are they recommended? Because directly inheriting built-in containers sometimes leads to pitfalls (for example, some built-in methods do not call the ones we rewrite).__setitem__), while inheritingUser*Classes can completely avoid such problems and make custom behavior more reliable.
An example of a custom dictionary "missing key hint" demonstrates its simplicity:
Summarize
BundlecollectionsThe core characters are recorded in a table for easy selection according to the scene at any time:
These tools can significantly improve the readability and performance of your code.
Next time you encounter similar needs, don’t rush to reinvent the wheel.collectionsDig around and chances are a ready-made solution is waiting for you there.

