← Interview prep

Python interview questions

Python language, data structures, and common interview traps.

100 questions · Page 4 of 5

Want the full pack? Interview packs · Mock interview · Mentora

Page 4 of 5

Questions 61–80 of 100 · 0 of 20 on this page marked learned

61.python-0061Hardsenior

Handle cancellation, timeouts and errors in asyncio with TaskGroup and timeout.

asyncio.TaskGroup runs tasks as a unit: if one fails, the others are cancelled and the errors are raised together as an ExceptionGroup, handled with except*. asyncio.timeout bounds how long a block may take and raises TimeoutError. Cancelled tasks receive CancelledError at their current await and should clean up in finally.

Full answer
python
import asyncio

async def job(name, delay, fail=False):
    try:
        await asyncio.sleep(delay)
        if fail:
            raise ValueError(f"{name} failed")
        return name
    except asyncio.CancelledError:
        print(f"{name} cancelled, cleaning up")
        raise

async def main():
    try:
        async with asyncio.TaskGroup() as tg:
            tg.create_task(job("slow", 1.0))
            tg.create_task(job("bad", 0.05, fail=True))
    except* ValueError as eg:
        print("errors:", [str(e) for e in eg.exceptions])
    try:
        async with asyncio.timeout(0.05):
            await job("too-long", 1.0)
    except TimeoutError:
        print("timed out")

asyncio.run(main())

Output:

text
slow cancelled, cleaning up
errors: ['bad failed']
too-long cancelled, cleaning up
timed out

When 'bad' raises, the TaskGroup cancels 'slow', which prints its cleanup message and re-raises CancelledError as it should, and then the group raises an ExceptionGroup containing the ValueError. except* picks out the ValueErrors. asyncio.timeout (Python 3.11+) cancels the awaited job after 0.05 seconds, so its own cleanup message prints first, and converts the cancellation into TimeoutError at the block boundary. Swallowing CancelledError breaks this machinery, so always re-raise it after cleanup.

python
import asyncio

async def job(name, delay, fail=False):
    try:
        await asyncio.sleep(delay)
        if fail:
            raise ValueError(f"{name} failed")
        return name
    except asyncio.CancelledError:
        print(f"{name} cancelled, cleaning up")
        raise

async def main():
    try:
        async with asyncio.TaskGroup() as tg:
            tg.create_task(job("slow", 1.0))
            tg.create_task(job("bad", 0.05, fail=True))
    except* ValueError as eg:
        print("errors:", [str(e) for e in eg.exceptions])
    try:
        async with asyncio.timeout(0.05):
            await job("too-long", 1.0)
    except TimeoutError:
        print("timed out")

asyncio.run(main())

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • TaskGroup cancels siblings on failure
  • Errors arrive as an ExceptionGroup
  • except* handles groups
  • asyncio.timeout bounds a block
  • Re-raise CancelledError after cleanup

Common mistakes

  • Catching and swallowing CancelledError
  • Using gather without handling partial failures

Follow-ups

  • How does asyncio.shield work?
  • How would you limit concurrency to 10 tasks?

Tips

  • Show the cancelled sibling
62.python-0062Hardsenior

Limit concurrency to N simultaneous requests in asyncio, for example when calling a rate-limited API.

Wrap each request in async with semaphore, where asyncio.Semaphore(N) allows at most N holders at once. Start all tasks, and they queue on the semaphore. For time-based limits, such as 10 requests per second, combine this with a token bucket or spacing between starts.

Full answer
python
import asyncio
active = 0
peak = 0

async def call_api(i, sem):
    global active, peak
    async with sem:
        active += 1
        peak = max(peak, active)
        await asyncio.sleep(0.02)
        active -= 1
        return i * i

async def main():
    sem = asyncio.Semaphore(3)
    results = await asyncio.gather(*(call_api(i, sem) for i in range(10)))
    print(results)
    print("peak concurrency:", peak)

asyncio.run(main())

Output:

text
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
peak concurrency: 3

Ten calls start at once, but the semaphore lets only three proceed at a time, so peak concurrency is 3. gather still returns results in input order. The shared counters are safe without a lock here because asyncio runs on one thread and the updates happen between awaits. For very large job lists, a fixed pool of worker tasks reading from an asyncio.Queue avoids creating thousands of pending tasks at once. HTTP clients such as httpx and aiohttp also offer connection limits.

python
import asyncio
active = 0
peak = 0

async def call_api(i, sem):
    global active, peak
    async with sem:
        active += 1
        peak = max(peak, active)
        await asyncio.sleep(0.02)
        active -= 1
        return i * i

async def main():
    sem = asyncio.Semaphore(3)
    results = await asyncio.gather(*(call_api(i, sem) for i in range(10)))
    print(results)
    print("peak concurrency:", peak)

asyncio.run(main())

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Semaphore caps simultaneous holders
  • gather keeps input order
  • Worker pools with a Queue scale better
  • Combine with time-based limits for rate caps
  • Single-threaded asyncio avoids data races between awaits

Common mistakes

  • Firing unlimited concurrent requests
  • Using threading.Semaphore in async code

Follow-ups

  • How would you implement 10 requests per second?
  • How do you retry with backoff in asyncio?

Tips

  • Measure the peak
63.python-0063Hardsenior

When should you use threads, processes or asyncio? Show ThreadPoolExecutor and ProcessPoolExecutor.

Use asyncio or threads for I/O-bound work (network, disk), since waiting releases the GIL; asyncio scales to many connections when async libraries exist, threads work with blocking libraries. Use processes for CPU-bound Python code to use several cores. concurrent.futures offers one interface for both pools.

Full answer
python
import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor

def io_task(i):
    time.sleep(0.1)
    return i

def cpu_task(n):
    return sum(i * i for i in range(n))

if __name__ == "__main__":
    t0 = time.perf_counter()
    with ThreadPoolExecutor(max_workers=5) as ex:
        print(list(ex.map(io_task, range(5))))
    print("threads overlap waits:", time.perf_counter() - t0 < 0.3)
    with ProcessPoolExecutor(max_workers=2) as ex:
        print(list(ex.map(cpu_task, [10**5, 10**5])))

Output:

text
[0, 1, 2, 3, 4]
threads overlap waits: True
[333328333350000, 333328333350000]

Five 0.1-second sleeps finish in about 0.1 seconds with five threads, because sleeping releases the GIL. The process pool computes two CPU-bound sums in separate processes, which can use two cores; arguments and results are pickled between processes, so they must be picklable and preferably small. The if __name__ == '__main__' guard is required for process pools on platforms that start workers by importing the main module. Process start-up costs time, so it pays off only for substantial work.

python
import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor

def io_task(i):
    time.sleep(0.1)
    return i

def cpu_task(n):
    return sum(i * i for i in range(n))

if __name__ == "__main__":
    t0 = time.perf_counter()
    with ThreadPoolExecutor(max_workers=5) as ex:
        print(list(ex.map(io_task, range(5))))
    print("threads overlap waits:", time.perf_counter() - t0 < 0.3)
    with ProcessPoolExecutor(max_workers=2) as ex:
        print(list(ex.map(cpu_task, [10**5, 10**5])))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Threads and asyncio for I/O-bound work
  • Processes for CPU-bound work
  • concurrent.futures unifies pools
  • Process arguments must be picklable
  • Guard process code with __main__

Common mistakes

  • Using threads for CPU-bound loops
  • Sending large objects to process pools

Follow-ups

  • What changes with the free-threaded build?
  • How would you share data between processes?

Tips

  • Classify the work first
64.python-0064Hardsenior

Design a retrying HTTP client wrapper for calls to a flaky third-party API.

Retry only idempotent requests and transient failures (timeouts, connection errors, 429 and 5xx), with exponential backoff and jitter, a maximum number of attempts and an overall deadline. Respect Retry-After headers, use idempotency keys for POSTs, log each retry, and add a circuit breaker so a dead dependency does not consume all workers.

Full answer
python
import random

class Transient(Exception): pass

def call_with_retry(fn, attempts=4, base=0.001, sleep=lambda s: None):
    for attempt in range(attempts):
        try:
            return fn()
        except Transient as e:
            if attempt == attempts - 1:
                raise
            delay = random.uniform(0, base * 2 ** attempt)
            print(f"attempt {attempt + 1} failed ({e}); retrying after jittered backoff")
            sleep(delay)

calls = {"n": 0}
def flaky():
    calls["n"] += 1
    if calls["n"] < 3:
        raise Transient("503")
    return "ok"
print(call_with_retry(flaky))

def bad_request():
    raise ValueError("400 bad request")
try:
    call_with_retry(bad_request)
except ValueError as e:
    print("not retried:", e)

Output:

text
attempt 1 failed (503); retrying after jittered backoff
attempt 2 failed (503); retrying after jittered backoff
ok
not retried: 400 bad request

The sketch retries a fake call that fails twice with a transient error and then succeeds; delays follow exponential backoff with full jitter, scaled down so the run is fast. A non-retryable error (a 400-style ValueError) fails immediately without retries.

Design points for production:

  • Classify errors: network errors, timeouts, HTTP 429, 502, 503 and 504 are retryable; 400, 401, 403 and 404 are not.
  • Backoff: delay = random.uniform(0, base * 2**attempt) (full jitter) prevents synchronised retry storms.
  • Limits: cap attempts and total time, and pass a timeout to every request.
  • Idempotency: retry POSTs only with an idempotency key the server honours.
  • Circuit breaker: after many consecutive failures, fail fast for a cool-down period.
  • Observability: count retries and failures per endpoint.

Libraries such as tenacity, or the retry options in urllib3 and httpx transports, implement much of this.

python
import random

class Transient(Exception): pass

def call_with_retry(fn, attempts=4, base=0.001, sleep=lambda s: None):
    for attempt in range(attempts):
        try:
            return fn()
        except Transient as e:
            if attempt == attempts - 1:
                raise
            delay = random.uniform(0, base * 2 ** attempt)
            print(f"attempt {attempt + 1} failed ({e}); retrying after jittered backoff")
            sleep(delay)

calls = {"n": 0}
def flaky():
    calls["n"] += 1
    if calls["n"] < 3:
        raise Transient("503")
    return "ok"
print(call_with_retry(flaky))

def bad_request():
    raise ValueError("400 bad request")
try:
    call_with_retry(bad_request)
except ValueError as e:
    print("not retried:", e)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Retry only transient errors
  • Exponential backoff with jitter
  • Cap attempts and total time
  • Idempotency keys for non-idempotent calls
  • Circuit breakers stop cascades

Common mistakes

  • Retrying every error, including 4xx
  • Retrying without jitter or limits

Follow-ups

  • How does a circuit breaker decide to close again?
  • How would you test retry logic?

Tips

  • Name the retryable status codes
65.python-0065Hardsenior

Design an in-process cache with time-to-live expiry and a size limit.

Use an OrderedDict keyed by the cache key, storing the value with its expiry time. On get, drop the entry if it has expired, otherwise move it to the end to mark it recently used. On set, insert or update and evict from the front while the cache exceeds its size. Add a lock if threads share it, and inject the clock for tests.

Full answer
python
from collections import OrderedDict

class TTLCache:
    def __init__(self, maxsize, ttl, clock):
        self.maxsize, self.ttl, self.clock = maxsize, ttl, clock
        self.data = OrderedDict()
    def get(self, key, default=None):
        item = self.data.get(key)
        if item is None:
            return default
        value, expires = item
        if self.clock() >= expires:
            del self.data[key]
            return default
        self.data.move_to_end(key)
        return value
    def set(self, key, value):
        self.data[key] = (value, self.clock() + self.ttl)
        self.data.move_to_end(key)
        while len(self.data) > self.maxsize:
            evicted, _ = self.data.popitem(last=False)
            print("evicted", evicted)

now = [0]
c = TTLCache(maxsize=2, ttl=10, clock=lambda: now[0])
c.set("a", 1); now[0] = 5; c.set("b", 2)
now[0] = 11
print(c.get("a"), c.get("b"))
c.set("c", 3); c.set("d", 4)
print(list(c.data))

Output:

text
None 2
evicted b
['c', 'd']

The fake clock makes expiry deterministic. At time 11, 'a' (stored at time 0 with a TTL of 10) has expired, so get returns None and deletes it, while 'b' is still valid. Adding 'c' fills the two slots, and adding 'd' evicts 'b', the least recently used entry, leaving 'c' and 'd'.

Points to discuss:

  • Complexity: OrderedDict gives O(1) get, set, move and pop.
  • Concurrency: guard operations with threading.Lock; for asyncio, avoid awaiting inside critical sections.
  • Stampedes: when a popular key expires, many callers recompute at once; a per-key lock or 'serve stale while refreshing' helps.
  • Memory: size limits by count are simple; limits by bytes need size estimates.
  • Multiple processes or servers need a shared cache such as Redis instead.

functools.lru_cache has no TTL, which is why a custom structure or a library like cachetools is used when expiry matters.

python
from collections import OrderedDict

class TTLCache:
    def __init__(self, maxsize, ttl, clock):
        self.maxsize, self.ttl, self.clock = maxsize, ttl, clock
        self.data = OrderedDict()
    def get(self, key, default=None):
        item = self.data.get(key)
        if item is None:
            return default
        value, expires = item
        if self.clock() >= expires:
            del self.data[key]
            return default
        self.data.move_to_end(key)
        return value
    def set(self, key, value):
        self.data[key] = (value, self.clock() + self.ttl)
        self.data.move_to_end(key)
        while len(self.data) > self.maxsize:
            evicted, _ = self.data.popitem(last=False)
            print("evicted", evicted)

now = [0]
c = TTLCache(maxsize=2, ttl=10, clock=lambda: now[0])
c.set("a", 1); now[0] = 5; c.set("b", 2)
now[0] = 11
print(c.get("a"), c.get("b"))
c.set("c", 3); c.set("d", 4)
print(list(c.data))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • OrderedDict gives O(1) LRU operations
  • Store expiry with each value
  • Inject the clock for testing
  • Lock for thread safety
  • Plan for stampedes

Common mistakes

  • Scanning all entries on every access
  • Using real time in tests

Follow-ups

  • How would you add stale-while-revalidate?
  • When would you move to Redis?

Tips

  • Show eviction order
66.python-0066Hardsenior

What are the hash and equality contracts, and what breaks when objects used as dict keys are mutable?

Objects that compare equal must have equal hashes, and an object's hash must not change while it is in a set or dict. If a key's hash depends on mutable fields and those fields change, lookups look in the wrong bucket and the entry becomes unreachable. Hash only immutable state, or make the class immutable.

Full answer
python
class Badge:
    def __init__(self, code): self.code = code
    def __eq__(self, other): return isinstance(other, Badge) and self.code == other.code
    def __hash__(self): return hash(self.code)

b = Badge("A1")
owners = {b: "Asha"}
b.code = "Z9"
print(Badge("A1") in owners, Badge("Z9") in owners, len(owners))
print([k.code for k in owners])

from dataclasses import dataclass
@dataclass(frozen=True)
class SafeBadge:
    code: str
s = SafeBadge("A1")
print({s: "Asha"}[SafeBadge("A1")])

Output:

text
False False 1
['Z9']
Asha

After b.code changes, the dict still stores the entry in the bucket for the old hash. Looking up Badge('A1') finds the bucket but the stored key no longer compares equal; looking up by the new code hashes to a different bucket. The entry is effectively lost although len(owners) is still 1 and iteration shows it. Even looking up with the same object b is unreliable: CPython checks identity first, so it succeeds only if the new hash happens to probe the old slot, which depends on the hash seed. The double run of this item caught exactly that, which is why the check is left out of the printout. A frozen dataclass makes the key immutable and generates a consistent __hash__ and __eq__. Python sets __hash__ to None when a class defines __eq__ alone, which prevents half of this mistake by default.

python
class Badge:
    def __init__(self, code): self.code = code
    def __eq__(self, other): return isinstance(other, Badge) and self.code == other.code
    def __hash__(self): return hash(self.code)

b = Badge("A1")
owners = {b: "Asha"}
b.code = "Z9"
print(Badge("A1") in owners, Badge("Z9") in owners, len(owners))
print([k.code for k in owners])

from dataclasses import dataclass
@dataclass(frozen=True)
class SafeBadge:
    code: str
s = SafeBadge("A1")
print({s: "Asha"}[SafeBadge("A1")])

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Equal objects need equal hashes
  • Hashes must not change while stored
  • Mutating keys loses entries
  • Frozen dataclasses give safe keys
  • Defining __eq__ alone disables hashing

Common mistakes

  • Hashing mutable fields
  • Defining __hash__ inconsistent with __eq__

Follow-ups

  • Why are lists unhashable but tuples hashable?
  • How are dict lookups implemented?

Tips

  • Explain the bucket lookup
67.python-0067Hardsenior

How do generators support send(), throw() and close(), and what is a coroutine-style generator used for?

send(value) resumes a generator and makes the paused yield expression evaluate to that value, so a generator can receive data as well as produce it. throw() raises an exception at the paused yield, and close() raises GeneratorExit so finally blocks run. These enable pipeline stages and running calculations, though async def has replaced generator-based coroutines for concurrency.

Full answer
python
def running_average():
    total = count = 0
    average = None
    try:
        while True:
            value = yield average
            total += value
            count += 1
            average = total / count
    finally:
        print("closed after", count, "values")

avg = running_average()
next(avg)
print(avg.send(10), avg.send(20), avg.send(60))
avg.close()

def worker():
    try:
        yield "ready"
    except ValueError as e:
        yield f"handled {e}"
w = worker()
print(next(w), w.throw(ValueError("bad input")))

Output:

text
10.0 15.0 30.0
closed after 3 values
ready handled bad input

The first next() primes the generator so it pauses at its first yield. Each send delivers a value and receives the updated average: 10.0, 15.0 and 30.0. close() triggers the finally block. throw raises inside the generator at the paused point, where it is caught and a new value is yielded. Forgetting to prime the generator raises TypeError: can't send non-None value to a just-started generator.

python
def running_average():
    total = count = 0
    average = None
    try:
        while True:
            value = yield average
            total += value
            count += 1
            average = total / count
    finally:
        print("closed after", count, "values")

avg = running_average()
next(avg)
print(avg.send(10), avg.send(20), avg.send(60))
avg.close()

def worker():
    try:
        yield "ready"
    except ValueError as e:
        yield f"handled {e}"
w = worker()
print(next(w), w.throw(ValueError("bad input")))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • send passes values into a paused generator
  • Prime with next() first
  • throw raises at the yield
  • close runs finally blocks
  • async def replaced generator coroutines

Common mistakes

  • Sending before priming
  • Swallowing GeneratorExit

Follow-ups

  • What does yield from add to send()?
  • How do async generators differ?

Tips

  • Show priming
68.python-0068Hardsenior

Reduce memory for millions of small objects with __slots__, and explain the trade-offs.

__slots__ declares a fixed set of attribute names, so instances store attributes in a compact array instead of a per-instance __dict__. That saves memory and slightly speeds attribute access, but instances cannot gain new attributes, and multiple inheritance with slots needs care. dataclass(slots=True) applies it automatically.

Full answer
python
import sys, tracemalloc
from dataclasses import dataclass

class PointDict:
    def __init__(self, x, y): self.x, self.y = x, y

class PointSlots:
    __slots__ = ("x", "y")
    def __init__(self, x, y): self.x, self.y = x, y

def measure(cls, n=100_000):
    tracemalloc.start()
    objs = [cls(i, i) for i in range(n)]
    size = tracemalloc.get_traced_memory()[0]
    tracemalloc.stop()
    return size

d, s = measure(PointDict), measure(PointSlots)
print("slots use less memory:", s < d)
p = PointSlots(1, 2)
try:
    p.z = 3
except AttributeError as e:
    print("AttributeError:", e)

@dataclass(slots=True)
class Reading:
    sensor: int
    value: float
print(hasattr(Reading(1, 2.0), "__dict__"))

Output:

text
slots use less memory: True
AttributeError: 'PointSlots' object has no attribute 'z' and no __dict__ for setting new attributes
False

Measured with tracemalloc, a hundred thousand slotted points use less memory than ordinary instances; the run prints a comparison rather than byte counts, which vary between builds. The gap is smaller on Python 3.11+ than on older versions, because ordinary instances now keep attributes inline and create a real __dict__ only when something asks for it, so measure on the version in production. Assigning an undeclared attribute fails, which can also catch typos. dataclass(slots=True) produces instances without __dict__. Trade-offs: no dynamic attributes, weak references need '__weakref__' in the slots, and every class in a hierarchy must declare slots for the saving to hold. For very large numeric data, arrays or NumPy beat any per-object layout.

python
import sys, tracemalloc
from dataclasses import dataclass

class PointDict:
    def __init__(self, x, y): self.x, self.y = x, y

class PointSlots:
    __slots__ = ("x", "y")
    def __init__(self, x, y): self.x, self.y = x, y

def measure(cls, n=100_000):
    tracemalloc.start()
    objs = [cls(i, i) for i in range(n)]
    size = tracemalloc.get_traced_memory()[0]
    tracemalloc.stop()
    return size

d, s = measure(PointDict), measure(PointSlots)
print("slots use less memory:", s < d)
p = PointSlots(1, 2)
try:
    p.z = 3
except AttributeError as e:
    print("AttributeError:", e)

@dataclass(slots=True)
class Reading:
    sensor: int
    value: float
print(hasattr(Reading(1, 2.0), "__dict__"))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Slots remove the per-instance __dict__
  • Large memory savings for many objects
  • No new attributes at runtime
  • dataclass(slots=True) applies it
  • Arrays beat objects for bulk numbers

Common mistakes

  • Adding slots to classes that need dynamic attributes
  • Forgetting slots in subclasses

Follow-ups

  • How do slots interact with inheritance?
  • When is NumPy the better answer?

Tips

  • Measure before and after
69.python-0069Hardsenior

Use contextvars to carry request-scoped data, such as a request id, through async code.

A ContextVar holds a value per execution context. asyncio tasks copy the current context when created, so setting a request id in one task does not leak into concurrent tasks, unlike a global variable or thread-local in async code. Frameworks use this for request ids, tenants and database sessions.

Full answer
python
import asyncio, contextvars
request_id = contextvars.ContextVar("request_id", default="-")

def log(msg):
    print(f"[{request_id.get()}] {msg}")

async def db_query():
    await asyncio.sleep(0.01)
    log("query done")

async def handle(rid, delay):
    request_id.set(rid)
    await asyncio.sleep(delay)
    await db_query()

async def main():
    await asyncio.gather(handle("req-1", 0.02), handle("req-2", 0.0))
    log("outside requests")

asyncio.run(main())

Output:

text
[req-2] query done
[req-1] query done
[-] outside requests

The two handlers interleave: req-2 finishes first because it does not wait at the start. Each log line still shows the right id, because each task created by gather runs in its own copy of the context, and db_query reads the value without it being passed as an argument. After both tasks, the main context still has the default '-'. A module-level global would show whichever request set it last. token = var.set(x) and var.reset(token) restore previous values in synchronous code.

python
import asyncio, contextvars
request_id = contextvars.ContextVar("request_id", default="-")

def log(msg):
    print(f"[{request_id.get()}] {msg}")

async def db_query():
    await asyncio.sleep(0.01)
    log("query done")

async def handle(rid, delay):
    request_id.set(rid)
    await asyncio.sleep(delay)
    await db_query()

async def main():
    await asyncio.gather(handle("req-1", 0.02), handle("req-2", 0.0))
    log("outside requests")

asyncio.run(main())

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • ContextVar values are per context
  • Tasks copy the context at creation
  • No leakage between concurrent requests
  • Use for request ids and tenants
  • reset with tokens restores values

Common mistakes

  • Using globals for request data in async servers
  • Thread-locals in asyncio code

Follow-ups

  • How does contextvars interact with thread pools?
  • How would you add the id to all log records?

Tips

  • Show interleaving with correct ids
70.python-0070Hardsenior

Why is pickle unsafe for untrusted data, and what should be used instead?

Unpickling can execute arbitrary code, because a pickle can instruct the loader to call any importable function with chosen arguments through __reduce__. Never unpickle data from users, networks or shared storage you do not fully control. Use JSON or another data-only format with validation, and sign data with hmac if integrity matters.

Full answer
python
import pickle, json

class Exploit:
    def __reduce__(self):
        return (print, ("code ran during unpickling",))

payload = pickle.dumps(Exploit())
pickle.loads(payload)

data = {"user": "asha", "roles": ["admin"]}
text = json.dumps(data)
print(json.loads(text))
try:
    json.loads('{"__reduce__": "os.system"}')["__reduce__"]()
except TypeError as e:
    print("JSON gives plain data only:", type(e).__name__)

Output:

text
code ran during unpickling
{'user': 'asha', 'roles': ['admin']}
JSON gives plain data only: TypeError

The harmless print stands in for something like os.system: simply loading the bytes called it. An attacker who can supply a pickle can therefore run commands with the program's permissions. JSON parsing produces only dicts, lists, strings, numbers, booleans and None, so a string that looks like a function name stays a string. Other risky patterns are eval on input, yaml.load without a safe loader, and subprocess with shell=True and user input. Pickle remains fine for trusted, internal data such as caches written and read by the same service.

python
import pickle, json

class Exploit:
    def __reduce__(self):
        return (print, ("code ran during unpickling",))

payload = pickle.dumps(Exploit())
pickle.loads(payload)

data = {"user": "asha", "roles": ["admin"]}
text = json.dumps(data)
print(json.loads(text))
try:
    json.loads('{"__reduce__": "os.system"}')["__reduce__"]()
except TypeError as e:
    print("JSON gives plain data only:", type(e).__name__)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Unpickling can run arbitrary code
  • Never unpickle untrusted data
  • Use JSON or validated formats
  • Sign data with hmac for integrity
  • Watch eval, unsafe YAML and shell=True

Common mistakes

  • Using pickle for API payloads or cookies
  • Assuming obscured pickles are safe

Follow-ups

  • How would you safely store Python objects in Redis?
  • What does yaml.safe_load prevent?

Tips

  • Demonstrate __reduce__
71.python-0071Hardsenior

Show how parameterised queries prevent SQL injection with sqlite3.

Building SQL by inserting user input into the string lets input change the query's structure. Pass values as parameters with placeholders (? or :name) so the driver sends them separately and they are always treated as data. Identifiers such as column names cannot be parameters; check them against an allow-list.

Full answer
python
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE users (name TEXT, is_admin INTEGER)")
con.executemany("INSERT INTO users VALUES (?, ?)", [("asha", 1), ("ben", 0)])
user_input = "nobody' OR '1'='1"

unsafe = f"SELECT name FROM users WHERE name = '{user_input}'"
print("unsafe:", con.execute(unsafe).fetchall())
print("safe:  ", con.execute("SELECT name FROM users WHERE name = ?", (user_input,)).fetchall())

def sorted_users(column):
    if column not in {"name", "is_admin"}:
        raise ValueError("bad sort column")
    return con.execute(f"SELECT name FROM users ORDER BY {column}").fetchall()
print(sorted_users("name"))
try:
    sorted_users("name; DROP TABLE users")
except ValueError as e:
    print("ValueError:", e)

Output:

text
unsafe: [('asha',), ('ben',)]
safe:   []
[('asha',), ('ben',)]
ValueError: bad sort column

The crafted input closes the quote and adds OR '1'='1', so the unsafe query returns every user. With a placeholder, the whole input is compared as a literal name and nothing matches. Sort columns cannot be passed as parameters, so the allow-list check is the safe way to build that part of the SQL. ORMs and query builders parameterise for you, but raw SQL fragments inside them carry the same risk.

python
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE users (name TEXT, is_admin INTEGER)")
con.executemany("INSERT INTO users VALUES (?, ?)", [("asha", 1), ("ben", 0)])
user_input = "nobody' OR '1'='1"

unsafe = f"SELECT name FROM users WHERE name = '{user_input}'"
print("unsafe:", con.execute(unsafe).fetchall())
print("safe:  ", con.execute("SELECT name FROM users WHERE name = ?", (user_input,)).fetchall())

def sorted_users(column):
    if column not in {"name", "is_admin"}:
        raise ValueError("bad sort column")
    return con.execute(f"SELECT name FROM users ORDER BY {column}").fetchall()
print(sorted_users("name"))
try:
    sorted_users("name; DROP TABLE users")
except ValueError as e:
    print("ValueError:", e)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Never format user input into SQL
  • Use ? or named placeholders
  • Parameters are always data
  • Allow-list identifiers
  • ORM raw fragments carry the same risk

Common mistakes

  • Escaping quotes by hand
  • Parameterising values but formatting column names from input

Follow-ups

  • How does executemany help with bulk inserts?
  • What other injection types exist?

Tips

  • Show the malicious input
72.python-0072Hardsenior

Design a plugin system so third parties can add exporters to an application without changing its code.

Define a small interface (a Protocol or ABC) for exporters, and discover implementations through package entry points (importlib.metadata.entry_points(group='app.exporters')) or a registry populated by __init_subclass__. Load plugins lazily, validate them against the interface, isolate failures so one bad plugin does not break the app, and version the interface.

Full answer
python
class Exporter:
    registry = {}
    def __init_subclass__(cls, fmt, **kw):
        super().__init_subclass__(**kw)
        Exporter.registry[fmt] = cls
    def export(self, rows):
        raise NotImplementedError

class CsvExporter(Exporter, fmt="csv"):
    def export(self, rows):
        return " | ".join(",".join(map(str, r)) for r in rows)

class BrokenExporter(Exporter, fmt="broken"):
    def export(self, rows):
        raise RuntimeError("plugin bug")

def run_export(fmt, rows):
    cls = Exporter.registry.get(fmt)
    if cls is None:
        return f"no exporter for {fmt}"
    try:
        return cls().export(rows)
    except Exception as e:
        return f"exporter {fmt!r} failed: {e}"

rows = [(1, "pen"), (2, "ink")]
print(sorted(Exporter.registry))
print(run_export("csv", rows))
print(run_export("broken", rows))
print(run_export("pdf", rows))

Output:

text
['broken', 'csv']
1,pen | 2,ink
exporter 'broken' failed: plugin bug
no exporter for pdf

The registry version shows the core idea: subclasses register themselves by format name, and the application looks them up without knowing the classes in advance. A broken plugin raises during export, and the application reports it instead of crashing.

For packages installed separately, entry points are the standard mechanism. A plugin package declares, in its pyproject.toml:

toml
[project.entry-points."app.exporters"]
pdf = "app_pdf.exporter:PdfExporter"

and the application runs for ep in entry_points(group="app.exporters"): registry[ep.name] = ep.load(). That snippet needs an installed plugin package, so it was not run here.

Further design points: keep the interface minimal and stable, pass plugins a narrow context object rather than the whole application, document a version and check compatibility at load time, and consider running untrusted plugins in a separate process.

python
class Exporter:
    registry = {}
    def __init_subclass__(cls, fmt, **kw):
        super().__init_subclass__(**kw)
        Exporter.registry[fmt] = cls
    def export(self, rows):
        raise NotImplementedError

class CsvExporter(Exporter, fmt="csv"):
    def export(self, rows):
        return " | ".join(",".join(map(str, r)) for r in rows)

class BrokenExporter(Exporter, fmt="broken"):
    def export(self, rows):
        raise RuntimeError("plugin bug")

def run_export(fmt, rows):
    cls = Exporter.registry.get(fmt)
    if cls is None:
        return f"no exporter for {fmt}"
    try:
        return cls().export(rows)
    except Exception as e:
        return f"exporter {fmt!r} failed: {e}"

rows = [(1, "pen"), (2, "ink")]
print(sorted(Exporter.registry))
print(run_export("csv", rows))
print(run_export("broken", rows))
print(run_export("pdf", rows))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Define a minimal interface
  • Discover via entry points or a registry
  • Load lazily and validate
  • Isolate plugin failures
  • Version the interface

Common mistakes

  • Importing every plugin at startup with no error handling
  • Exposing internal objects to plugins

Follow-ups

  • How would you sandbox untrusted plugins?
  • How does pytest discover its plugins?

Tips

  • Name entry points
73.python-0073Hardsenior

Decimal or float for a billing system? Show how to compute GST and rounding correctly.

Use Decimal (constructed from strings) or integer paise for money, never float. Apply tax line by line or on the total according to the invoice rule, and round with an explicit mode, typically ROUND_HALF_UP to two places, at defined points. Keep the rounding rule in one function so every path agrees.

Full answer
python
from decimal import Decimal, ROUND_HALF_UP, getcontext
PAISA = Decimal("0.01")

def money(x):
    return Decimal(x).quantize(PAISA, rounding=ROUND_HALF_UP)

lines = [("Notebook", Decimal("45.50"), 3), ("Pen", Decimal("9.99"), 7)]
gst = Decimal("0.18")
subtotal = sum((price * qty for _, price, qty in lines), Decimal("0"))
per_line = sum(money(price * qty * gst) for _, price, qty in lines)
on_total = money(subtotal * gst)
print(subtotal, per_line, on_total)
f = 0.0
for _ in range(10):
    f += 0.1
print(f, sum([Decimal("0.1")] * 10))
print(getcontext().prec)

Output:

text
206.43 37.16 37.16
0.9999999999999999 1.0
28

The subtotal is exactly 206.43. Rounding tax per line gives 37.16, while rounding once on the total gives 37.16 as well here, but the two methods can differ by a paisa on other baskets, so the invoice rule must be chosen explicitly and applied consistently. Adding 0.1 ten times in a float loop gives 0.9999999999999999, while Decimals sum to exactly 1.0. (The built-in sum uses compensated summation since Python 3.12 and would print 1.0 for floats, which hides the error rather than removing it.) The default Decimal context has 28 significant digits, ample for currency. Passing Decimal(x) a float would import its binary error, which is why money receives Decimals or strings.

python
from decimal import Decimal, ROUND_HALF_UP, getcontext
PAISA = Decimal("0.01")

def money(x):
    return Decimal(x).quantize(PAISA, rounding=ROUND_HALF_UP)

lines = [("Notebook", Decimal("45.50"), 3), ("Pen", Decimal("9.99"), 7)]
gst = Decimal("0.18")
subtotal = sum((price * qty for _, price, qty in lines), Decimal("0"))
per_line = sum(money(price * qty * gst) for _, price, qty in lines)
on_total = money(subtotal * gst)
print(subtotal, per_line, on_total)
f = 0.0
for _ in range(10):
    f += 0.1
print(f, sum([Decimal("0.1")] * 10))
print(getcontext().prec)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Decimal from strings or integer paise
  • Explicit rounding mode
  • Decide per-line or total tax rounding
  • Centralise rounding
  • Floats accumulate errors

Common mistakes

  • Using float for money
  • Rounding at different points in different code paths

Follow-ups

  • How would you split a payment into three equal parts?
  • How should money be stored in a database?

Tips

  • Show float versus Decimal
74.python-0074Hardsenior

A Python web service's memory grows steadily until it is restarted. How do you investigate?

Confirm the growth with metrics, then compare memory snapshots over time: tracemalloc snapshots show which lines allocate the growing memory, and gc or objgraph show which object types increase. Usual causes are unbounded caches, lists or dicts that keep growing, references held by closures or global registries, and C extensions. Fix the retention, then verify with a load test.

Full answer
python
import tracemalloc
LEAK = []
def handle_request(i):
    payload = "x" * 10_000
    LEAK.append(payload)
    return len(payload)

tracemalloc.start()
for i in range(50): handle_request(i)
before = tracemalloc.take_snapshot()
for i in range(500): handle_request(i)
after = tracemalloc.take_snapshot()
top = after.compare_to(before, "lineno")[0]
print("top growth at line", top.traceback[0].lineno, "| grew by more than 4 MB:", top.size_diff > 4_000_000)

Output:

text
top growth at line 4 | grew by more than 4 MB: True

The run simulates a leak: a module-level list keeps every request's payload. Comparing two tracemalloc snapshots taken before and after a batch of requests points at line 4, which creates each payload: tracemalloc reports where memory was allocated, and the list is what keeps those allocations alive. In a real service the next step is to find what holds references to objects allocated at the reported line.

A practical sequence:

  1. Check whether memory plateaus (normal allocator behaviour, caches warming) or grows without bound.
  2. Reproduce with a load test locally or on a staging copy.
  3. Take tracemalloc snapshots a few minutes apart and compare with compare_to(..., 'lineno').
  4. Inspect growing object types with gc.get_objects() counts or objgraph.
  5. Typical fixes: bound caches (lru_cache(maxsize=...)), clear per-request state, remove event-listener registrations, avoid storing request objects in globals.
  6. If Python-level memory is flat but the process grows, suspect C extensions or fragmentation; tools such as memray help.

Restarting workers periodically (for example gunicorn's max_requests) is a mitigation, not a fix.

python
import tracemalloc
LEAK = []
def handle_request(i):
    payload = "x" * 10_000
    LEAK.append(payload)
    return len(payload)

tracemalloc.start()
for i in range(50): handle_request(i)
before = tracemalloc.take_snapshot()
for i in range(500): handle_request(i)
after = tracemalloc.take_snapshot()
top = after.compare_to(before, "lineno")[0]
print("top growth at line", top.traceback[0].lineno, "| grew by more than 4 MB:", top.size_diff > 4_000_000)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Confirm unbounded growth first
  • Compare tracemalloc snapshots
  • Track growing object types
  • Common causes are unbounded containers and caches
  • Periodic restarts only mitigate

Common mistakes

  • Restarting forever without investigating
  • Assuming the garbage collector is broken

Follow-ups

  • How does memray differ from tracemalloc?
  • Why might memory not return to the OS after objects are freed?

Tips

  • Compare snapshots
75.python-0075Hardsenior

Design a background job worker in Python that processes tasks from a queue reliably.

Workers pull jobs from a durable queue (Redis, RabbitMQ, SQS or a database table), process them, and acknowledge only after success, so crashes cause redelivery. Make handlers idempotent, retry with backoff and a dead-letter queue after N failures, handle SIGTERM by finishing the current job, and bound concurrency. Monitor queue depth, failures and job duration.

Full answer
python
from collections import deque
queue = deque([("send_email", 0), ("flaky_report", 0), ("broken_job", 0)])
failures = {"flaky_report": 2}
dead_letter, done, shutting_down = [], [], False

def handle(name):
    if name == "broken_job":
        raise RuntimeError("always fails")
    if failures.get(name, 0) > 0:
        failures[name] -= 1
        raise RuntimeError("transient")
    return f"{name} ok"

while queue and not shutting_down:
    name, attempts = queue.popleft()
    try:
        done.append(handle(name))
    except RuntimeError as e:
        if attempts + 1 >= 3:
            dead_letter.append((name, str(e)))
        else:
            queue.append((name, attempts + 1))
    if len(done) == 2 and not queue:
        shutting_down = True
print(done)
print(dead_letter)
print("stopped cleanly:", shutting_down or not queue)

Output:

text
['send_email ok', 'flaky_report ok']
[('broken_job', 'always fails')]
stopped cleanly: True

The run uses an in-memory queue to show the control flow: a job that fails twice is retried and then succeeds, a job that always fails lands in the dead-letter list after three attempts, and a shutdown flag stops the loop cleanly between jobs.

Production concerns:

  • Delivery is at least once, so handlers must tolerate duplicates (idempotency keys, upserts).
  • Acknowledge after the work commits; with a database queue, mark done in the same transaction as the business change.
  • Visibility timeouts: if a worker dies mid-job, the job becomes visible again after a timeout.
  • Graceful shutdown: on SIGTERM, stop taking new jobs and finish or requeue the current one.
  • Concurrency: processes for CPU-heavy jobs, threads or asyncio for I/O-heavy ones.
  • Scheduling and priorities: separate queues per priority rather than one mixed queue.

Celery, RQ, Dramatiq and arq implement these patterns; knowing them helps evaluate which to use.

python
from collections import deque
queue = deque([("send_email", 0), ("flaky_report", 0), ("broken_job", 0)])
failures = {"flaky_report": 2}
dead_letter, done, shutting_down = [], [], False

def handle(name):
    if name == "broken_job":
        raise RuntimeError("always fails")
    if failures.get(name, 0) > 0:
        failures[name] -= 1
        raise RuntimeError("transient")
    return f"{name} ok"

while queue and not shutting_down:
    name, attempts = queue.popleft()
    try:
        done.append(handle(name))
    except RuntimeError as e:
        if attempts + 1 >= 3:
            dead_letter.append((name, str(e)))
        else:
            queue.append((name, attempts + 1))
    if len(done) == 2 and not queue:
        shutting_down = True
print(done)
print(dead_letter)
print("stopped cleanly:", shutting_down or not queue)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Acknowledge after success
  • Idempotent handlers for at-least-once delivery
  • Retries with backoff and dead-letter queues
  • Graceful shutdown on SIGTERM
  • Monitor depth, failures and duration

Common mistakes

  • Acknowledging before processing
  • Non-idempotent handlers with automatic retries

Follow-ups

  • How would you schedule a job for later?
  • How do visibility timeouts work in SQS?

Tips

  • State the delivery guarantee
76.python-0076Hardsenior

How does Python's import system find and load modules, and how can import time be reduced?

import checks sys.modules first; if the module is not cached, finders on sys.meta_path locate it through sys.path, a loader executes the module's code once, and the module object is cached. Startup cost comes from executing heavy top-level code. Measure with python -X importtime and defer expensive imports into the functions that need them.

Full answer
python
import subprocess, sys
r = subprocess.run([sys.executable, "-X", "importtime", "-c", "import json"], capture_output=True, text=True)
lines = [l for l in r.stderr.splitlines() if l.startswith("import time:")]
print(lines[0].split("|")[-1].strip(), "...", lines[-1].split("|")[-1].strip())
print("json" in sys.modules)
import json
print("json" in sys.modules, json.__spec__.origin.endswith("json/__init__.py"))
print(sys.meta_path[0].__name__, len(sys.meta_path) >= 3)

Output:

text
imported package ... json
False
True True
BuiltinImporter True

-X importtime prints a line per module with self and cumulative microseconds; the run shows only the header and the last module name, since times vary. Before import json in this process, json is not in sys.modules; afterwards it is, and its spec records where it was loaded from. sys.meta_path holds the finders, starting with the built-in importer. For command-line tools, moving imports of heavy libraries (pandas, boto3) inside functions can cut startup from seconds to milliseconds. Python 3.12+ also caches more in .pyc files, but executing module bodies still costs time.

python
import subprocess, sys
r = subprocess.run([sys.executable, "-X", "importtime", "-c", "import json"], capture_output=True, text=True)
lines = [l for l in r.stderr.splitlines() if l.startswith("import time:")]
print(lines[0].split("|")[-1].strip(), "...", lines[-1].split("|")[-1].strip())
print("json" in sys.modules)
import json
print("json" in sys.modules, json.__spec__.origin.endswith("json/__init__.py"))
print(sys.meta_path[0].__name__, len(sys.meta_path) >= 3)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • sys.modules caches imports
  • Finders on sys.meta_path locate modules
  • Module code runs once
  • -X importtime measures cost
  • Defer heavy imports

Common mistakes

  • Heavy work at module import time
  • Circular imports between modules

Follow-ups

  • How does importlib.reload behave?
  • What are lazy imports?

Tips

  • Show importtime
77.python-0077Hardsenior

A Django or FastAPI endpoint is slow under load. Walk through how you would find and fix the cause as a senior engineer.

Start from measurements: per-endpoint latency percentiles and traces that split time between database, external calls and Python code. Most slow endpoints are slowed by queries (N+1 patterns, missing indexes), blocking calls inside async code, or serialisation of large payloads. Fix the dominant cost, add a regression test or budget, and re-measure under the same load.

Full answer
python
import sqlite3
con = sqlite3.connect(":memory:")
con.executescript(
    "CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT);"
    "CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER);")
con.executemany("INSERT INTO customers VALUES (?, ?)", [(i, f"c{i}") for i in range(5)])
con.executemany("INSERT INTO orders VALUES (?, ?)", [(i, i % 5) for i in range(20)])
count = {"n": 0}
con.set_trace_callback(lambda sql: count.__setitem__("n", count["n"] + 1))

orders = con.execute("SELECT id, customer_id FROM orders").fetchall()
names = [con.execute("SELECT name FROM customers WHERE id = ?", (cid,)).fetchone()[0] for _, cid in orders]
print("N+1 queries:", count["n"])

count["n"] = 0
orders = con.execute("SELECT id, customer_id FROM orders").fetchall()
ids = sorted({cid for _, cid in orders})
marks = ",".join("?" * len(ids))
lookup = dict(con.execute(f"SELECT id, name FROM customers WHERE id IN ({marks})", ids).fetchall())
names2 = [lookup[cid] for _, cid in orders]
print("batched queries:", count["n"], names == names2)

Output:

text
N+1 queries: 21
batched queries: 2 True

The run contrasts an N+1 access pattern with a batched one using an in-memory SQLite database, counting queries rather than timing them: 21 queries for 20 orders versus 2. The same counting approach works in tests for real services.

Investigation checklist:

  • Tracing (OpenTelemetry, APM): which spans dominate for slow requests?
  • Database: query counts per request, slow query logs, EXPLAIN for the worst query.
  • Async misuse: a blocking driver or time.sleep inside an async endpoint stalls the event loop for every request.
  • External calls: missing timeouts, sequential calls that could run concurrently.
  • Payloads: serialising thousands of rows; paginate and select only needed fields.
  • Workers: too few processes for CPU-bound work, or too many for the database's connection limit.

Then fix, add a query-count assertion or latency budget in CI, and confirm with a load test (for example locust) before and after.

python
import sqlite3
con = sqlite3.connect(":memory:")
con.executescript(
    "CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT);"
    "CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER);")
con.executemany("INSERT INTO customers VALUES (?, ?)", [(i, f"c{i}") for i in range(5)])
con.executemany("INSERT INTO orders VALUES (?, ?)", [(i, i % 5) for i in range(20)])
count = {"n": 0}
con.set_trace_callback(lambda sql: count.__setitem__("n", count["n"] + 1))

orders = con.execute("SELECT id, customer_id FROM orders").fetchall()
names = [con.execute("SELECT name FROM customers WHERE id = ?", (cid,)).fetchone()[0] for _, cid in orders]
print("N+1 queries:", count["n"])

count["n"] = 0
orders = con.execute("SELECT id, customer_id FROM orders").fetchall()
ids = sorted({cid for _, cid in orders})
marks = ",".join("?" * len(ids))
lookup = dict(con.execute(f"SELECT id, name FROM customers WHERE id IN ({marks})", ids).fetchall())
names2 = [lookup[cid] for _, cid in orders]
print("batched queries:", count["n"], names == names2)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Measure with traces and percentiles
  • Database access dominates most slow endpoints
  • Blocking calls stall async servers
  • Paginate and trim payloads
  • Guard fixes with tests and budgets

Common mistakes

  • Optimising Python code before checking queries
  • Load testing different scenarios before and after

Follow-ups

  • How would you detect blocking calls in asyncio?
  • How do you size worker processes?

Tips

  • Count queries per request
78.python-0078Easyfresher

What does this program print, given that integers are immutable and lists are mutable?

Rebinding an integer parameter inside a function does not change the caller's variable, because the function only rebinds its local name. Mutating a list through a parameter does change the caller's list, because both names refer to the same object. Assigning a new list to the parameter, rather than mutating it, again leaves the caller unchanged.

Full answer
python
def bump(n, items, other):
    n += 1
    items.append(n)
    other = other + [n]
    return n

count, log, extra = 1, [], []
result = bump(count, log, extra)
print(count, result, log, extra)

Output:

text
1 2 [2] []

n += 1 makes the local n refer to a new integer 2; count outside is still 1. items.append mutates the list object shared with log, so log becomes [2]. other = other + [n] builds a new list and binds only the local name, so extra stays empty. Python passes references to objects, and what matters is whether the function mutates the object or rebinds the name.

python
def bump(n, items, other):
    n += 1
    items.append(n)
    other = other + [n]
    return n

count, log, extra = 1, [], []
result = bump(count, log, extra)
print(count, result, log, extra)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Parameters are names bound to the caller's objects
  • Rebinding a parameter is local
  • Mutation is visible to the caller
  • + creates a new list, append mutates
  • Ints and strings are immutable

Common mistakes

  • Expecting n += 1 to change the caller's int
  • Assuming other + [...] mutates the list

Follow-ups

  • What would other += [n] do instead?
  • How do you avoid mutating an argument?

Tips

  • Separate rebinding from mutation
79.python-0079Easyfresher

Use for-else and while with break to find the first prime above a number.

A for or while loop can have an else block, which runs only when the loop ends without break. That fits search loops: break when the item is found, and use else for the not-found case. while True with break suits loops whose stopping point is not known in advance.

Full answer
python
def is_prime(n):
    if n < 2:
        return False
    for d in range(2, int(n ** 0.5) + 1):
        if n % d == 0:
            break
    else:
        return True
    return False

def next_prime(n):
    candidate = n + 1
    while True:
        if is_prime(candidate):
            return candidate
        candidate += 1

print([n for n in range(20) if is_prime(n)])
print(next_prime(90), next_prime(97))

Output:

text
[2, 3, 5, 7, 11, 13, 17, 19]
97 101

In is_prime, the else attached to the for runs only when no divisor triggered break, so it returns True for primes. Checking divisors up to the square root is enough, because any larger divisor pairs with a smaller one. next_prime keeps testing candidates in a while True loop and returns as soon as one is prime: 97 after 90 and 101 after 97. Many developers misread for-else, so a short comment or a helper function with an early return is often the clearer choice in team code.

python
def is_prime(n):
    if n < 2:
        return False
    for d in range(2, int(n ** 0.5) + 1):
        if n % d == 0:
            break
    else:
        return True
    return False

def next_prime(n):
    candidate = n + 1
    while True:
        if is_prime(candidate):
            return candidate
        candidate += 1

print([n for n in range(20) if is_prime(n)])
print(next_prime(90), next_prime(97))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Loop else runs when no break happened
  • Useful for search loops
  • Check divisors up to the square root
  • while True with return or break for open-ended loops
  • Prefer clarity if the team finds for-else confusing

Common mistakes

  • Thinking else runs when the loop body never executes only
  • Checking every divisor up to n

Follow-ups

  • How would you generate primes up to a million efficiently?
  • How does break interact with try and finally?

Tips

  • Explain when else runs
80.python-0080Easyfresher

Find the duplicate values in a list while keeping the order in which they first repeat.

Walk the list once with a set of values seen so far; when a value is already in the set and not yet reported, record it. This is O(n) time, unlike the O(n squared) approach of calling list.count for every item. Counter works when order does not matter.

Full answer
python
from collections import Counter

def duplicates(items):
    seen, reported, result = set(), set(), []
    for x in items:
        if x in seen and x not in reported:
            result.append(x)
            reported.add(x)
        seen.add(x)
    return result

orders = ["pen", "ink", "pen", "pad", "ink", "pen", "cap"]
print(duplicates(orders))
print(sorted(k for k, v in Counter(orders).items() if v > 1))
print(list(dict.fromkeys(orders)))

Output:

text
['pen', 'ink']
['ink', 'pen']
['pen', 'ink', 'pad', 'cap']

'pen' repeats at position 2 and 'ink' at position 4, so the result lists them in that order, and the third 'pen' is not reported again because of the reported set. The Counter version finds the same values, sorted here for a stable display. dict.fromkeys is the related idiom for removing duplicates while keeping first-seen order, since dicts preserve insertion order. Set membership checks are O(1) on average, which keeps the whole scan linear.

python
from collections import Counter

def duplicates(items):
    seen, reported, result = set(), set(), []
    for x in items:
        if x in seen and x not in reported:
            result.append(x)
            reported.add(x)
        seen.add(x)
    return result

orders = ["pen", "ink", "pen", "pad", "ink", "pen", "cap"]
print(duplicates(orders))
print(sorted(k for k, v in Counter(orders).items() if v > 1))
print(list(dict.fromkeys(orders)))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Track seen values in a set
  • O(n) instead of repeated count()
  • Report each duplicate once
  • Counter when order does not matter
  • dict.fromkeys removes duplicates in order

Common mistakes

  • Calling items.count(x) inside a loop
  • Using set() when order matters

Follow-ups

  • How would you find duplicates in a file too big for memory?
  • How would you return counts too?

Tips

  • State the complexity