This answer key contains 4 multiple-choice, 4 fill-in-the-blank, and 4 output-prediction questions for Python collections, with the exact answer and a short explanation for every question.
The answers are shown in full, so use this page after making an attempt. The practice page is the better first pass.
What does Counter(votes) return?
Answer: A mapping of values to counts
Why: Counter is a dictionary subclass whose values are occurrence counts.
What does this code print?
from collections import Counter
print(Counter("aba")["a"])Answer: 2
Why: The string has two a characters, and a missing key would return zero.
What does defaultdict(list) do for a missing key?
Answer: Creates an empty list
Why: The list factory supplies the default value and inserts the key.
Which deque call removes the leftmost item?
Answer: popleft()
Why: popleft removes and returns the item at the left end of the deque.
Complete the import for the counting container.
from collections import ____
print(Counter(["a", "a"]))Answer: Counter
Why: Counter is the counting dictionary in collections.
Complete the method that returns the most common entries.
from collections import Counter
counts = Counter(["a", "b", "a"])
print(counts.____(1))Answer: most_common
Why: most_common returns entries ordered by descending count.
Complete the factory for a list-valued defaultdict.
from collections import defaultdict
groups = defaultdict(____)Answer: list
Why: Passing list creates an empty list for a missing key.
Complete the call that removes the oldest queue item.
from collections import deque
queue = deque([1, 2])
queue.____()Answer: popleft
Why: popleft removes from the left end of a deque.
What does the program output?
from collections import Counter
print(Counter("abca")["a"])Answer: 2
Why: The character a appears twice.
What appears on the screen?
from collections import Counter
print(Counter([1, 1, 2]).most_common(1))Answer: [(1, 2)]
Why: The most common entry is 1 with a count of 2.
What is printed?
from collections import defaultdict
d = defaultdict(list)
d["x"].append(1)
print(dict(d))Answer: {'x': [1]}
Why: The missing key receives an empty list, which then gets one item.
What is the output?
from collections import deque
q = deque([1, 2, 3])
q.popleft()
print(list(q))Answer: [2, 3]
Why: popleft removes the first item, leaving two and three.
Try the questions first
Open the practice page for Python collections and answer the same 12 questions with instant feedback.