typestar

The collections module in Python

Counter, defaultdict, and deque for everyday jobs.

from collections import Counter, defaultdict, deque

votes = ["yes", "no", "yes", "yes", "no", "maybe"]
tally = Counter(votes)
winner, count = tally.most_common(1)[0]

groups = defaultdict(list)
for word in ["ant", "bee", "bear", "ale"]:
    groups[word[0]].append(word)

recent = deque(maxlen=3)
for n in range(6):
    recent.append(n)

How it works

  1. Counter tallies items; most_common ranks them.
  2. defaultdict(list) groups without key checks.
  3. deque(maxlen=3) keeps a rolling window.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
328
Tokens
115
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 66 seconds.

Type this snippet

Step 3 of 5 in Data formats, step 19 of 41 in Domain tools.

← Previous Next →