Recipes: Collections¶
Task-focused how-tos. If you know what you want to do but aren't sure how to build it, this is the section to skim.
Recipes in this section¶
- Count and tally items — frequency counts from any iterable, the top-N most common, counting with a condition, and combining or differencing counts with
Counterarithmetic. - Group items with defaultdict — turn a flat list into a
{key: [items]}mapping, group into sets, build an index, and nest groups — plus whensetdefaultoritertools.groupbyfits better. - Build a queue or sliding window — a FIFO queue, a bounded history of the last N items, a moving average over a window, and an undo stack — all with
deque. - Avoid common collections mistakes — a catalogue of the traps:
defaultdictcreating keys when you only read, dropped items frommaxlen,Counterquirks, namedtuple immutability, and reaching for alistwhere adequebelongs.