Collections Basics

Preview — 3 of 10 questions

What is the output of the following code?

javascript
from collections import Counter

votes = ["red", "blue", "red", "green", "blue", "red"]
tally = Counter(votes)
print(tally)
print(tally.most_common(1))
ACounter({'red': 3, 'blue': 2, 'green': 1}) then [('red', 3), ('blue', 2)]
BCounter({'red': 1, 'blue': 1, 'green': 1}) then [('red', 1)]
CCounter({'red': 3, 'blue': 2, 'green': 1}) then [('red', 3)]
D{'red': 3, 'blue': 2, 'green': 1} then [('red', 3)]

What is the output of the following code?

javascript
from collections import defaultdict

d = defaultdict(int)
d["a"] += 1
d["a"] += 1
d["b"] += 1

print(dict(d))
print(len(d))
A{'a': 2, 'b': 1} then 2
B{'a': 1, 'b': 1} then 2
C{'a': 2, 'b': 1} then 3
DKeyError

What is the output of the following code?

javascript
from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])
p = Point(1, 2)

print(p.x, p[1])
p.x = 10
ATypeError: 'Point' object does not support item access
B1 2, then 10 is set successfully
C1 1, then AttributeError
D1 2, then AttributeError: can't set attribute

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.