×

python · level 3 · unit 4 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Pick a set or dictionary and a search becomes one step.

A set or dictionary does not search item after item. It works out a , a quick fingerprint of the value, which says exactly where to look. So x in a_set takes about one step, whether it holds ten items or ten million.

The collections module has two dictionaries built for common jobs. A tallies things and ranks them with most_common. A makes an empty list for any new key, so grouping needs no checks.

from collections import Counter, defaultdict

orders = [("Ana", "tea"), ("Ben", "cake"), ("Ana", "scone"), ("Cara", "tea")]
regulars = {"Ana", "Cara"}
print([who for who, item in orders if who in regulars])
print(Counter(item for who, item in orders).most_common(1))
by_person = defaultdict(list)
for who, item in orders:
    by_person[who].append(item)
print(dict(by_person))

Sets and dictionaries buy their speed with memory, so keep a list when order and repeats matter.