SyntaxPilot
Courses/Python Coding Questions/Lesson 29
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Python Coding Questions · Lesson 29 of 30

Machine coding round

a tiny key-value store with TTL and an event emitter (on, off, emit)tested with unittest

These are the notes for Python Coding Questions, episode 29: the machine coding round. Instead of one puzzle, you build a small working system in about an hour, and you prove it works with tests. Today: a key-value store whose keys expire (TTL) and an event emitter (on, off, emit), both tested with unittest.

Every program was run with Python 3.13 (python3 main.py), the SyntaxPilot compiler's Python command. Every output below is real.

Words for today:

  • Machine coding round: an interview round where you write a small, complete, working program (often 60-90 minutes), graded on correctness, readability, tests and extensibility.
  • API (application programming interface): the part of your code other code uses: class names, method names, inputs and outputs.
  • Key-value store: a store that maps keys to values, like a dictionary (set(key, value), get(key)).
  • TTL (time to live): how many seconds a key stays valid after it is set.
  • OTP (one-time password): a short code sent to you that works once, for a short time.
  • Dependency injection: passing an object the things it depends on (here, a clock) from outside instead of creating or calling them inside.
  • Fake clock: a clock you control in tests, so you can "move time" without waiting.
  • Unit test: a small automatic check of one piece of code. unittest is Python's built-in testing framework.
  • Event emitter: an object that lets functions subscribe to named events (on) and calls them when the event is emitted (emit).
  • Handler (listener, callback): a function that runs when an event happens.
  • Observer pattern: the design where many observers subscribe to one subject and are told when something happens.

How the round works

Step What to do Example today
1. Requirements Ask what it must and need not do Must keys expire exactly on time? Is ttl=0 allowed?
2. API Name the class, methods, inputs, outputs Store.set(key, value, ttl=None), Store.get(key, default=None)
3. Code The simplest version that works, clear names a dict of (value, end_time)
4. Tests Prove it, edge cases first expiry at 119 vs 120 seconds, ttl=0, len()

Graded on: working, readable, tested, extensible.

Q1: A key-value store with TTL

Real-life example: a banking app sends Asha the OTP 4821, valid for 2 minutes. After that, get("asha") must behave as if the key was never there.

Attempt 1: store the expiry time

import time

class Store:
    def __init__(self):
        self.data = {}

    def set(self, key, value, ttl=None):
        expires = time.time() + ttl if ttl else None
        self.data[key] = (value, expires)

    def get(self, key, default=None):
        if key not in self.data:
            return default
        value, expires = self.data[key]
        return value

otp = Store()
otp.set("asha", "4821", ttl=2)          # an OTP, valid 2 seconds
print(otp.get("asha"))
time.sleep(3)
print(otp.get("asha"))                   # should be gone

Output:

4821
4821

After sleeping 3 seconds, the 2-second OTP is still returned: a security bug. We saved the expiry time but get() never checks it. And to test a 2-minute OTP this way, the test would have to sleep for 2 minutes.

The fix: check the time in get(), and inject the clock

  • get() compares the clock with the end time; if it's over, delete the key and return the default.
  • ttl=None means "never expires"; ttl=0 means "expires at once". Write if ttl is None, not if ttl (0 is falsy, so if ttl would make a 0-second key live forever).
  • The store takes a clock function: the real app passes time.monotonic (a clock that never jumps backwards, unlike time.time(), which can change when the system clock is corrected); tests pass a fake clock.
class Store:
    def __init__(self, clock):
        self.clock, self.data = clock, {}
    def set(self, key, value, ttl=None):
        end = None if ttl is None else self.clock() + ttl
        self.data[key] = (value, end)
    def get(self, key, default=None):
        value, end = self.data.get(key, (default, None))
        if end is not None and self.clock() >= end:
            del self.data[key]                  # expired: forget it
            return default
        return value

now = 0                                         # a fake clock: we move time
otp = Store(clock=lambda: now)
otp.set("asha", "4821", ttl=120)                # valid for 2 minutes
otp.set("ravi", "7730")                         # no ttl: never expires
otp.set("neha", "1111", ttl=0)                  # expires at once
now = 119
print(otp.get("asha"), otp.get("ravi"), otp.get("neha"))
now = 120
print(otp.get("asha"), otp.get("ravi"), otp.get("nobody", "-"))

Output:

4821 7730 None
None 7730 -

At 119 s: 4821, 7730, and None for Neha (ttl=0). At 120 s: Asha's OTP is gone, exactly on time; Ravi's stays; a missing key gives the default -. set and get are O(1).

The if ttl trap:

def set_key(store, key, value, ttl=None):
    end = 100 + ttl if ttl else None          # bug: 0 is falsy
    store[key] = (value, end)

s = {}
set_key(s, "neha", "1111", ttl=0)
print(s)

Output:

{'neha': ('1111', None)}

unittest in one minute

import unittest

class TestStore(unittest.TestCase):     # a group of tests
    def setUp(self):                    # runs before EVERY test
        ...
    def test_something(self):           # each test_... method is one test
        self.assertEqual(got, expected)

unittest.main()                         # find and run them all
Result Mark Meaning
pass . (or ok with verbosity=2) every assert held
FAIL F an assert was wrong (AssertionError)
ERROR E the code raised an exception

Useful asserts: assertEqual(a, b), assertIsNone(x), assertTrue(x), assertRaises(Error).

Test 1: len() counts expired keys

import unittest

class Store:
    def __init__(self, clock):
        self.clock, self.data = clock, {}
    def set(self, key, value, ttl=None):
        end = None if ttl is None else self.clock() + ttl
        self.data[key] = (value, end)
    def get(self, key, default=None):
        value, end = self.data.get(key, (default, None))
        if end is not None and self.clock() >= end:
            del self.data[key]                  # expired: forget it
            return default
        return value
    def __len__(self):
        return len(self.data)

class TestStore(unittest.TestCase):
    def setUp(self):                            # runs before every test
        self.now = 0
        self.s = Store(clock=lambda: self.now)
        self.s.set("asha", "4821", ttl=120)
        self.s.set("ravi", "7730")

    def test_get(self):
        self.now = 120
        self.assertIsNone(self.s.get("asha"))
        self.assertEqual(self.s.get("ravi"), "7730")

    def test_len_skips_expired(self):
        self.now = 500
        self.assertEqual(len(self.s), 1)

unittest.main()

Output:

.F
======================================================================
FAIL: test_len_skips_expired (__main__.TestStore.test_len_skips_expired)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "main.py", line 32, in test_len_skips_expired
    self.assertEqual(len(self.s), 1)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^
AssertionError: 2 != 1

----------------------------------------------------------------------
Ran 2 tests in 0.005s

FAILED (failures=1)

AssertionError: 2 != 1: expired keys are only removed when someone calls get() on them, so len() still counts Asha's OTP.

Test 2: delete while looping over the dict

Let len() call get() on every key (which drops expired ones):

import unittest

class Store:
    def __init__(self, clock):
        self.clock, self.data = clock, {}
    def set(self, key, value, ttl=None):
        end = None if ttl is None else self.clock() + ttl
        self.data[key] = (value, end)
    def get(self, key, default=None):
        value, end = self.data.get(key, (default, None))
        if end is not None and self.clock() >= end:
            del self.data[key]                  # expired: forget it
            return default
        return value
    def __len__(self):
        for key in self.data:
            self.get(key)                       # drops the key if expired
        return len(self.data)

class TestStore(unittest.TestCase):
    def setUp(self):                            # runs before every test
        self.now = 0
        self.s = Store(clock=lambda: self.now)
        self.s.set("asha", "4821", ttl=120)
        self.s.set("ravi", "7730")

    def test_get(self):
        self.now = 120
        self.assertIsNone(self.s.get("asha"))
        self.assertEqual(self.s.get("ravi"), "7730")

    def test_len_skips_expired(self):
        self.now = 500
        self.assertEqual(len(self.s), 1)

unittest.main()

Output:

.E
======================================================================
ERROR: test_len_skips_expired (__main__.TestStore.test_len_skips_expired)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "main.py", line 34, in test_len_skips_expired
    self.assertEqual(len(self.s), 1)
                     ~~~^^^^^^^^
  File "main.py", line 16, in __len__
    for key in self.data:
               ^^^^^^^^^
RuntimeError: dictionary changed size during iteration

----------------------------------------------------------------------
Ran 2 tests in 0.010s

FAILED (errors=1)

RuntimeError: dictionary changed size during iteration: we deleted from the dictionary we were looping over, so Python stops the loop rather than lose its place. (It's an ERROR, E, not a FAIL: the code crashed.)

The fix: loop over a copy of the keys

import unittest

class Store:
    def __init__(self, clock):
        self.clock, self.data = clock, {}
    def set(self, key, value, ttl=None):
        end = None if ttl is None else self.clock() + ttl
        self.data[key] = (value, end)
    def get(self, key, default=None):
        value, end = self.data.get(key, (default, None))
        if end is not None and self.clock() >= end:
            del self.data[key]                  # expired: forget it
            return default
        return value
    def __len__(self):
        for key in list(self.data):             # a copy: get() may delete
            self.get(key)                       # drops the key if expired
        return len(self.data)

class TestStore(unittest.TestCase):
    def setUp(self):                            # runs before every test
        self.now = 0
        self.s = Store(clock=lambda: self.now)
        self.s.set("asha", "4821", ttl=120)
        self.s.set("ravi", "7730")

    def test_get(self):
        self.now = 120
        self.assertIsNone(self.s.get("asha"))
        self.assertEqual(self.s.get("ravi"), "7730")

    def test_len_skips_expired(self):
        self.now = 500
        self.assertEqual(len(self.s), 1)

unittest.main()

Output:

..
----------------------------------------------------------------------
Ran 2 tests in 0.005s

OK

list(self.data) makes a copy of the keys, so deleting from the dict is safe. Ran 2 tests, OK. len() is O(n), which is fine here; a production store might clean up expired keys in the background instead.

Q2: An event emitter

Real-life example: a doorbell. It doesn't know who is home; it just rings ("emits") with who is at the door. The dog barks, mom opens the door: each subscribed (on). A guest can stop listening (off).

Method What it does
on(event, fn) subscribe fn to event
off(event, fn) unsubscribe it
emit(event, *args) call every handler of event, in order, with args

Attempt 1: a dict of lists

class Emitter:
    def __init__(self):
        self.handlers = {}                      # event -> list of functions
    def on(self, event, fn):
        self.handlers.setdefault(event, []).append(fn)
    def off(self, event, fn):
        self.handlers[event].remove(fn)
    def emit(self, event, *args):
        for fn in self.handlers.get(event, []):
            fn(*args)

bell = Emitter()
bell.on("ring", lambda who: print("dog barks at", who))
bell.on("ring", lambda who: print("mom opens the door for", who))
bell.emit("ring", "the milkman")
bell.emit("knock", "nobody")                    # no handlers: nothing

Output:

dog barks at the milkman
mom opens the door for the milkman

Both handlers run, in the order they subscribed, and an event nobody listens to does nothing. Looks done, so test it.

The tests catch two bugs

import unittest

class Emitter:
    def __init__(self):
        self.handlers = {}                      # event -> list of functions
    def on(self, event, fn):
        self.handlers.setdefault(event, []).append(fn)
    def off(self, event, fn):
        self.handlers[event].remove(fn)
    def emit(self, event, *args):
        for fn in self.handlers.get(event, []):
            fn(*args)

class TestEmitter(unittest.TestCase):
    def test_off_inside_a_handler(self):
        e, calls = Emitter(), []
        def once(x):                            # runs once, then unsubscribes
            calls.append("once")
            e.off("ring", once)
        e.on("ring", once)
        e.on("ring", lambda x: calls.append("log"))
        e.emit("ring", 1)
        self.assertEqual(calls, ["once", "log"])

    def test_off_unknown(self):
        e = Emitter()
        e.off("ring", print)                    # never added: no crash

unittest.main()

Output:

FE
======================================================================
ERROR: test_off_unknown (__main__.TestEmitter.test_off_unknown)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "main.py", line 27, in test_off_unknown
    e.off("ring", print)                    # never added: no crash
    ~~~~~^^^^^^^^^^^^^^^
  File "main.py", line 9, in off
    self.handlers[event].remove(fn)
    ~~~~~~~~~~~~~^^^^^^^
KeyError: 'ring'

======================================================================
FAIL: test_off_inside_a_handler (__main__.TestEmitter.test_off_inside_a_handler)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "main.py", line 23, in test_off_inside_a_handler
    self.assertEqual(calls, ["once", "log"])
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Lists differ: ['once'] != ['once', 'log']

Second list contains 1 additional elements.
First extra element 1:
'log'

- ['once']
+ ['once', 'log']

----------------------------------------------------------------------
Ran 2 tests in 0.005s

FAILED (failures=1, errors=1)
  • ERROR, KeyError: 'ring': off() looked up an event that has no list yet.
  • FAIL, Lists differ: ['once'] != ['once', 'log']: the log handler was skipped.

Why was it skipped? The loop is at index 0 and calls once, which removes itself. log slides down from index 1 to index 0, and the loop moves on to index 1, where there is nothing. A list gives no error, it silently skips: worse than the dictionary's RuntimeError.

Step List Loop index
start [once, log] 0 → calls once
once removes itself [log] next index is 1
loop ends [log] log never called

The fix: emit over a copy; off ignores unknown handlers

import unittest

class Emitter:
    def __init__(self):
        self.handlers = {}                      # event -> list of functions
    def on(self, event, fn):
        self.handlers.setdefault(event, []).append(fn)
    def off(self, event, fn):
        if fn in self.handlers.get(event, []):  # unknown: just ignore
            self.handlers[event].remove(fn)
    def emit(self, event, *args):
        for fn in list(self.handlers.get(event, [])):   # a copy
            fn(*args)

class TestEmitter(unittest.TestCase):
    def test_order_and_args(self):
        e, got = Emitter(), []
        e.on("ring", lambda w: got.append("dog " + w))
        e.on("ring", lambda w: got.append("mom " + w))
        e.emit("ring", "milkman")
        self.assertEqual(got, ["dog milkman", "mom milkman"])

    def test_off_inside_a_handler(self):
        e, calls = Emitter(), []
        def once(x):                            # runs once, then unsubscribes
            calls.append("once")
            e.off("ring", once)
        e.on("ring", once)
        e.on("ring", lambda x: calls.append("log"))
        e.emit("ring", 1)
        self.assertEqual(calls, ["once", "log"])

    def test_off_unknown(self):
        e = Emitter()
        e.off("ring", print)                    # never added: no crash

unittest.main(verbosity=2)

Output:

test_off_inside_a_handler (__main__.TestEmitter.test_off_inside_a_handler) ... ok
test_off_unknown (__main__.TestEmitter.test_off_unknown) ... ok
test_order_and_args (__main__.TestEmitter.test_order_and_args) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.003s

OK

3 tests OK. on is O(1), emit is O(h) for h handlers, off is O(h).

Common mistakes (and what you really see)

Mistake What you see Why Fix
storing the expiry, never checking it an expired OTP still works get() ignores the time check in get(), delete if over
if ttl: ttl=0 lives forever 0 is falsy if ttl is None
time.sleep(120) in a test a 2-minute test real time inject a fake clock
time.time() for expiry expiry jumps when the system clock is changed wall-clock time can move back time.monotonic
deleting from a dict while looping it RuntimeError: dictionary changed size during iteration the loop loses its place for key in list(d):
removing from a list while looping it a handler silently skipped items slide down loop over a copy
self.handlers[event].remove(fn) KeyError: 'ring' no list for that event check first, ignore unknown
tests that share state a test passes alone, fails with others one test spoils another build fresh objects in setUp

Your turn: once() and a capacity limit (solution)

Questions: (1) Emitter.once(event, fn): fn runs on the next emit only. (2) Store(clock, capacity=2): when full, drop the key that expires soonest (keys that never expire are dropped last).

Ideas: once wraps fn in a small function that calls off first, then fn (this only works because emit loops over a copy). The capacity check uses len(self), which already drops expired keys, so they don't count.

import unittest

class Emitter:
    def __init__(self):
        self.handlers = {}
    def on(self, event, fn):
        self.handlers.setdefault(event, []).append(fn)
    def off(self, event, fn):
        if fn in self.handlers.get(event, []):
            self.handlers[event].remove(fn)
    def emit(self, event, *args):
        for fn in list(self.handlers.get(event, [])):
            fn(*args)
    def once(self, event, fn):
        def wrapper(*args):
            self.off(event, wrapper)            # unsubscribe first
            fn(*args)
        self.on(event, wrapper)

class Store:
    def __init__(self, clock, capacity=None):
        self.clock, self.data, self.capacity = clock, {}, capacity
    def set(self, key, value, ttl=None):
        if self.capacity and key not in self.data and len(self) >= self.capacity:
            soonest = min(self.data, key=lambda k: self.data[k][1]
                          if self.data[k][1] is not None else float("inf"))
            del self.data[soonest]              # evict the key expiring soonest
        end = None if ttl is None else self.clock() + ttl
        self.data[key] = (value, end)
    def get(self, key, default=None):
        value, end = self.data.get(key, (default, None))
        if end is not None and self.clock() >= end:
            del self.data[key]
            return default
        return value
    def __len__(self):
        for key in list(self.data):
            self.get(key)
        return len(self.data)

class TestExtensions(unittest.TestCase):
    def test_once(self):
        e, calls = Emitter(), []
        e.once("ring", calls.append)
        e.emit("ring", 1)
        e.emit("ring", 2)
        self.assertEqual(calls, [1])

    def test_capacity_evicts_soonest(self):
        now = [0]
        s = Store(clock=lambda: now[0], capacity=2)
        s.set("asha", "4821", ttl=120)
        s.set("ravi", "7730", ttl=60)           # expires sooner
        s.set("neha", "1111", ttl=300)          # full: ravi is dropped
        self.assertIsNone(s.get("ravi"))
        self.assertEqual((s.get("asha"), s.get("neha"), len(s)), ("4821", "1111", 2))

    def test_capacity_counts_only_alive_keys(self):
        now = [0]
        s = Store(clock=lambda: now[0], capacity=2)
        s.set("asha", "4821", ttl=10)
        s.set("ravi", "7730")
        now[0] = 50                             # asha has expired
        s.set("neha", "1111")
        self.assertEqual((s.get("ravi"), s.get("neha")), ("7730", "1111"))

unittest.main(verbosity=2)

Output:

test_capacity_counts_only_alive_keys (__main__.TestExtensions.test_capacity_counts_only_alive_keys) ... ok
test_capacity_evicts_soonest (__main__.TestExtensions.test_capacity_evicts_soonest) ... ok
test_once (__main__.TestExtensions.test_once) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK

Mini project: an OTP service

Both pieces together: the TTL store holds the codes, the emitter announces what happened (for logs, alerts, analytics), and an OTP works only once.

import time

class Emitter:
    def __init__(self):
        self.handlers = {}
    def on(self, event, fn):
        self.handlers.setdefault(event, []).append(fn)
    def emit(self, event, *args):
        for fn in list(self.handlers.get(event, [])):
            fn(*args)

class Store:
    def __init__(self, clock):
        self.clock, self.data = clock, {}
    def set(self, key, value, ttl=None):
        end = None if ttl is None else self.clock() + ttl
        self.data[key] = (value, end)
    def get(self, key, default=None):
        value, end = self.data.get(key, (default, None))
        if end is not None and self.clock() >= end:
            del self.data[key]
            return default
        return value

class OTPService:
    """Sends an OTP, checks it once, and announces what happened."""
    def __init__(self, clock=time.monotonic):
        self.codes, self.events = Store(clock), Emitter()
    def send(self, user, code):
        self.codes.set(user, code, ttl=120)
        self.events.emit("sent", user)
    def verify(self, user, code):
        ok = code == self.codes.get(user)
        if ok:
            self.codes.set(user, None, ttl=0)   # an OTP works only once
        self.events.emit("verified" if ok else "rejected", user)
        return ok

now = 0
otp = OTPService(clock=lambda: now)
for name in ("sent", "verified", "rejected"):
    otp.events.on(name, lambda user, name=name: print(f"[{name}] {user}"))
otp.send("asha", "4821")
print(otp.verify("asha", "1234"), otp.verify("asha", "4821"), otp.verify("asha", "4821"))
otp.send("ravi", "7730")
now = 121                                       # 2 minutes and 1 second later
print(otp.verify("ravi", "7730"))

Output:

[sent] asha
[rejected] asha
[verified] asha
[rejected] asha
False True False
[sent] ravi
[rejected] ravi
False

Practice questions (with solutions)

1. A rate limiter: at most 5 requests per minute per user.

Solution

Keep a deque of request times per user; drop the ones older than the window, then allow the request if fewer than limit remain (a sliding window, as in episode 26). Amortised O(1) per request.

from collections import deque

class RateLimiter:
    """At most `limit` requests per `window` seconds, per user (sliding window)."""
    def __init__(self, limit, window, clock):
        self.limit, self.window, self.clock = limit, window, clock
        self.hits = {}                          # user -> deque of request times
    def allow(self, user):
        now, q = self.clock(), self.hits.setdefault(user, deque())
        while q and q[0] <= now - self.window:  # forget requests that are too old
            q.popleft()
        if len(q) < self.limit:
            q.append(now)
            return True
        return False

t = [0]
rl = RateLimiter(limit=5, window=60, clock=lambda: t[0])
print([rl.allow("asha") for _ in range(6)])
t[0] = 59
print(rl.allow("asha"), rl.allow("ravi"))
t[0] = 60
print(rl.allow("asha"))

Output:

[True, True, True, True, True, False]
False True
True

2. An LRU cache with TTL (episode 25's LRU cache, plus expiry).

Solution

OrderedDict keeps keys in order of use: move_to_end on every use, popitem(last=False) drops the least recently used. Each entry also stores its end time.

from collections import OrderedDict

class TTLLRUCache:
    def __init__(self, capacity, ttl, clock):
        self.capacity, self.ttl, self.clock = capacity, ttl, clock
        self.data = OrderedDict()               # key -> (value, end), oldest use first
    def get(self, key, default=None):
        if key not in self.data:
            return default
        value, end = self.data[key]
        if self.clock() >= end:
            del self.data[key]
            return default
        self.data.move_to_end(key)              # just used: now the newest
        return value
    def put(self, key, value):
        self.data[key] = (value, self.clock() + self.ttl)
        self.data.move_to_end(key)
        if len(self.data) > self.capacity:
            self.data.popitem(last=False)       # drop the least recently used

t = [0]
c = TTLLRUCache(capacity=2, ttl=100, clock=lambda: t[0])
c.put("a", 1); c.put("b", 2)
c.get("a")                                      # a is now newer than b
c.put("c", 3)                                   # full: b is dropped
print(c.get("a"), c.get("b"), c.get("c"))
t[0] = 100
print(c.get("a"), c.get("c"))

Output:

1 None 3
None None

3. Pub/sub with wildcard topics like "order.*".

Solution

fnmatch matches shell-style patterns (* = anything). Publishing loops over a copy of the subscriptions, for the same reason as the emitter.

from fnmatch import fnmatch

class PubSub:
    def __init__(self):
        self.subs = []                          # (pattern, handler)
    def subscribe(self, pattern, fn):
        self.subs.append((pattern, fn))
    def publish(self, topic, msg):
        for pattern, fn in list(self.subs):
            if fnmatch(topic, pattern):         # "order.*" matches "order.paid"
                fn(topic, msg)

bus = PubSub()
bus.subscribe("order.*", lambda t, m: print("orders team:", t, m))
bus.subscribe("order.paid", lambda t, m: print("kitchen:", t, m))
bus.subscribe("*", lambda t, m: print("log:", t))
bus.publish("order.paid", "#42 masala dosa")
bus.publish("user.signup", "neha")

Output:

orders team: order.paid #42 masala dosa
kitchen: order.paid #42 masala dosa
log: order.paid
log: user.signup

Quick quiz

What does this print?

nums = [1, 2, 2, 3]
for n in nums:
    if n == 2:
        nums.remove(n)
print(nums)

(A) [1, 3] (B) [1, 2, 3] (C) RuntimeError (D) [1, 2, 2, 3]

Answer

(B). The first 2 (index 1) is removed; the second 2 slides into index 1, and the loop moves on to index 2 (the 3). The safe way is to build a new list:

nums = [1, 2, 2, 3]
for n in nums:
    if n == 2:
        nums.remove(n)
print(nums)
nums = [1, 2, 2, 3]
print([n for n in nums if n != 2])

Output:

[1, 2, 3]
[1, 3]

Interview questions

  1. What do interviewers look for in a machine coding round? Clarified requirements, a clean API, working code, sensible names, tests for edge cases, and code that's easy to extend.
  2. How do you test code that depends on time? Inject the clock (dependency injection) and pass a fake clock in tests; never sleep.
  3. time.time() vs time.monotonic()? time() is wall-clock time and can jump when the clock is adjusted; monotonic() only moves forward, so it's right for measuring durations and expiry.
  4. Lazy vs eager expiry? Lazy: delete an expired key when it's read (our get). Eager: a background job removes expired keys. Real stores like Redis combine both.
  5. FAIL vs ERROR in unittest? FAIL: an assertion was false. ERROR: the code raised an unexpected exception.
  6. What is setUp for? It runs before every test and builds fresh objects, so tests don't depend on each other.
  7. Why does deleting from a dict while iterating raise an error? The dict's size changes under the iterator; Python detects it and raises RuntimeError rather than return wrong results.
  8. Why is removing from a list while iterating dangerous? Items shift left and the loop skips one, with no error.
  9. What is the observer pattern? Many observers subscribe to a subject and are notified on events; the subject doesn't need to know who they are. Event emitters, GUI buttons and webhooks use it.
  10. How would you make the store thread-safe? Protect set, get and len with a threading.Lock.

Glossary

Term Meaning Example
Machine coding round Build a small working system in an interview today's store and emitter
Requirements What the system must (and need not) do keys expire after ttl seconds
API Names, inputs and outputs other code uses set(key, value, ttl=None)
Key-value store Maps keys to values {"asha": "4821"}
TTL Time to live, in seconds ttl=120
OTP One-time password 4821
Expiry / end time The moment a key stops being valid clock() + ttl
Falsy Treated as False in if 0, None, ""
Dependency injection Passing dependencies in from outside Store(clock=...)
Fake clock A clock the test controls lambda: self.now
time.monotonic A clock that never goes backwards real expiry
Unit test An automatic check of one piece of code test_get
unittest.TestCase Base class for a group of tests class TestStore(...)
setUp Runs before every test a fresh store
Assertion A check inside a test assertEqual(len(s), 1)
FAIL / ERROR / OK Wrong answer / crash / all passed .F, .E, OK
RuntimeError Raised for a dict changed during iteration deleting in for key in d
Copy of a list A new list with the same items list(d), list(handlers)
Event A named thing that happens "ring"
Event emitter Calls subscribed handlers on emit bell.emit("ring", who)
Handler / callback A function run on an event lambda who: print(...)
Subscribe / unsubscribe Start / stop listening on / off
Observer pattern Many listeners, one subject the doorbell
setdefault Get a key, creating it with a default first setdefault(event, [])
Capacity / eviction A size limit / removing an item to make room drop the key expiring soonest

Summary

  • Machine coding round: requirements → API → code → tests. Working, readable, tested, extensible.
  • TTL store: store (value, end_time); check the time in get() and delete expired keys; ttl is None, not if ttl; inject the clock and use a fake clock in tests.
  • unittest: TestCase, setUp, assertEqual/assertIsNone; F = wrong answer, E = crash.
  • Changing what you loop over: a dict raises RuntimeError, a list silently skips; loop over a copy.
  • Event emitter: a dict of handler lists; emit over a copy; off ignores unknown handlers.
  • Next episode, the last of this series: tricky output questions: is vs ==, 0.1 + 0.2, mutable default arguments, late binding and more.