10. π Checkpoint: names, objects, and collections
Predict the output, then run the code. If you get one wrong, re-read the chapter in brackets.
# 1. [Ch 2]
a = [1, 2]
b = a
a = a + [3]
print(b)
# 2. [Ch 2]
a = [1, 2]
b = a
a += [3]
print(b)
# 3. [Ch 2.6]
def f(x, acc={}):
acc[x] = True
return len(acc)
print(f("a"), f("b"), f("a"))
# 4. [Ch 5.4]
fs = []
for i in range(3):
fs.append(lambda: i * 10)
print([g() for g in fs])
# 5. [Ch 3.5]
print([] or {} or 0 or "x")
# 6. [Ch 6.4]
d = {}
d[(1, 2)] = "tuple ok"
try:
d[[1, 2]] = "list?"
except TypeError as e:
print(type(e).__name__)
Answers
[1, 2].a + [3]builds a new list and rebindsa;bstill names the old one.[1, 2, 3].+=on a list mutates in place, andbnames the same object.1 2 2. The default dict is created once and shared between calls.[20, 20, 20]. The lambdas capture the variablei, read after the loop ends.x.orreturns the first truthy operand.TypeError. Lists are mutable and unhashable, so they cannot be dict keys.
Exercises:
- Write
dedupe(items)that removes duplicates but keeps first-seen order, in one line. (Hint:dict.fromkeys.) - Write
chunks(xs, n)that splits a list into lists of lengthn, the last one possibly shorter. - Given a list of
(user, bytes_sent)tuples, return the top 3 users by total bytes, usingCounter. - Explain, in two sentences, why
def f(x=[])is a bug anddef f(x=())is not.