Frontend Labs
β‹―

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. [1, 2]. a + [3] builds a new list and rebinds a; b still names the old one.
  2. [1, 2, 3]. += on a list mutates in place, and b names the same object.
  3. 1 2 2. The default dict is created once and shared between calls.
  4. [20, 20, 20]. The lambdas capture the variable i, read after the loop ends.
  5. x. or returns the first truthy operand.
  6. TypeError. Lists are mutable and unhashable, so they cannot be dict keys.

Exercises:

  1. Write dedupe(items) that removes duplicates but keeps first-seen order, in one line. (Hint: dict.fromkeys.)
  2. Write chunks(xs, n) that splits a list into lists of length n, the last one possibly shorter.
  3. Given a list of (user, bytes_sent) tuples, return the top 3 users by total bytes, using Counter.
  4. Explain, in two sentences, why def f(x=[]) is a bug and def f(x=()) is not.

Generated from real-life-python-guide.md Β· 8 Oct 2026 16:36