Intermediate · Errors, modules and the standard library · topic 25 of 50 · 25 min
collections and itertools
Explanation
Counter: counting made easy
from collections import Counter
votes = ["chai", "coffee", "chai", "lassi", "chai", "coffee"]
count = Counter(votes)
print(count["chai"])
print(count.most_common(2))
print(Counter("banana"))defaultdict: no more KeyError
from collections import defaultdict
people = [("Asha", "Pune"), ("Ravi", "Delhi"), ("Meena", "Pune")]
by_city = defaultdict(list)
for name, city in people:
by_city[city].append(name) # no need to check if city exists
print(dict(by_city))
spend = defaultdict(int)
spend["food"] += 250
print(spend["food"], spend["travel"])namedtuple: tuples with names
from collections import namedtuple
Student = namedtuple("Student", ["name", "city", "marks"])
s = Student("Asha", "Pune", 88)
print(s.name, s.marks)
print(s[1])deque: a queue open at both ends
from collections import deque
recent = deque(maxlen=3)
for search in ["phone", "charger", "cover", "earphones"]:
recent.append(search)
print(list(recent))
queue = deque(["Ravi", "Asha"])
queue.append("Meena") # joins at the back
print(queue.popleft()) # served from the frontitertools: tools for looping
| Function | Gives you | Example result |
|---|---|---|
| count(1) | 1, 2, 3, ... forever | numbering with zip |
| chain(a, b) | a then b, as one sequence | chain([1, 2], [3]) → 1, 2, 3 |
| combinations(x, 2) | groups where order does not matter | AB, AC, BC |
| permutations(x, 2) | arrangements where order matters | AB, AC, BA, BC, CA, CB |
| product(a, b) | every pair, one from each | S-red, S-blue, M-red, M-blue |
| groupby(x, key) | runs of neighbouring items with the same key | needs sorted data |
from itertools import count, chain, combinations, permutations, product
for n, name in zip(count(1), ["Asha", "Ravi", "Meena"]):
print(n, name)
print(list(chain([1, 2], [3], [4, 5])))
print(list(combinations(["A", "B", "C"], 2)))
print(len(list(permutations(["A", "B", "C"], 2))))
print(list(product(["S", "M"], ["red", "blue"])))groupby: sort first!
from itertools import groupby
sales = [("fruit", 40), ("veg", 30), ("fruit", 25), ("veg", 10)]
sales.sort(key=lambda s: s[0])
for category, rows in groupby(sales, key=lambda s: s[0]):
total = 0
for _, amount in rows:
total += amount
print(category, total)Watch the lesson
collections and itertools · 1/6
Python has two modules full of ready-made tools for counting, grouping and looping. They save you a lot of code.
Prefer a video by a teacher? Find free videos on “python collections counter defaultdict itertools tutorial” on YouTube ↗
In real life: Which items sell most at a kirana shop?
Farhan writes down every item sold in a day. At closing time he wants the top three items and the money taken per category. Counter answers the first question in one line, and defaultdict adds up the money without any "if key not in dict" checks.
from collections import Counter, defaultdict
sold = [("milk", "dairy", 30), ("bread", "bakery", 40), ("milk", "dairy", 30),
("curd", "dairy", 25), ("milk", "dairy", 30), ("bread", "bakery", 40)]
items = Counter()
for name, _, _ in sold:
items[name] += 1
print(items.most_common(3))
money = defaultdict(int)
for _, category, price in sold:
money[category] += price
print(dict(money))Practice (0/3 done)
Write top_items(items, n) that returns the n most common items with their counts, as a list of (item, count) pairs, most common first. Use Counter.
Write group_by_city(people) where people is a list of (name, city) pairs. Return a normal dict that maps each city to the list of names from that city, in the order they appear. Use defaultdict(list).
Write team_pairs(players) that returns a list of every possible pair of players as tuples, where order does not matter (A with B is the same team as B with A). Use itertools.
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.