Chapters
Python114 chapters

Exercises

The collections Module

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

Print the two most common letters in the word, using Counter.

Python
# import Counter and print the top two of "mississippi"
Exercise 2

Use a defaultdict so no key check is needed.

Python
from collections import defaultdict

pairs = [("maths", "ada"), ("maths", "grace")]
groups = {}
for subject, name in pairs:
    groups[subject].append(name)

print(dict(groups))
Exercise 3

Keep only the last three readings, using a deque that discards the rest for you.

Python
from collections import deque

last_three = deque()
for n in range(6):
    last_three.append(n)

print(list(last_three))