
Counter — count occurrences:
from collections import Counter
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
count = Counter(words)
count["apple"] # 3
count.most_common(2) # [("apple", 3), ("banana", 2)]defaultdict — dict with default values:
from collections import defaultdict
graph = defaultdict(list)
graph["A"].append("B") # No KeyError even if "A" didn't exist
word_count = defaultdict(int)
for word in words:
word_count[word] += 1 # No KeyError for new keysdeque — double-ended queue:
from collections import deque q = deque([1, 2, 3]) q.appendleft(0) # add to front q.append(4) # add to back q.popleft() # remove from front (O(1) vs list O(n))
namedtuple — tuple with named fields:
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
p.x # 3
p.y # 4Reference:
TaskLoco™ — The Sticky Note GOAT