Library
Interview prep — revise the course as questions
This is the whole course turned sideways: the same material as the full guide, but asked the way an interviewer asks it. Each question has a tight answer and, where code makes it concrete, a runnable snippet with its real output. The weighting matches real interviews — heavier on language fundamentals, OOP, and internals (Stages 1–3) and on DSA patterns (Stage 4); Stage 5 gets a short set of track-level talking points instead of code, since that stage is "pick one" by design. Read a question, answer it out loud, then check yourself against the snippet. Every section ends with a "Revise with" link back to the parts that cover it in depth.
All code below runs unmodified on Python 3.14. Lines marked (varies) depend on your machine or on set/dict iteration order and will differ from run to run; everything else is the exact output.
Stage 1: Foundation
Q. What's the real difference between mutable and immutable objects?
A mutable object's value can change in place after creation (list, dict, set, and your own classes by default); an immutable one cannot (int, float, str, tuple, bool, frozenset). = never copies — it just binds a name to whatever object already exists — so two names pointing at the same mutable object will both see any in-place change made through either name. Immutability is also what makes a value usable as a dict key or set member (see hashability, below).
Q. is vs == — when do you use each?
== calls __eq__ and asks "do these have the same value?"; is compares id() and asks "are these the very same object in memory?" Use is only for singleton checks (x is None, x is True), never for numbers or strings, because whether two equal numbers/strings happen to be the same object is an implementation detail, not a language guarantee.
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # True
print(a is b) # False
print(a is c) # True
Q. Why can 1000 is 1000 look True on one line but False when the numbers are built at runtime?
CPython caches small integers (-5 to 256) as permanent singletons, so those always pass is. Outside that range, two literals typed in the same statement can end up as the same cached constant purely because the compiler deduplicates identical constants within one code object — an implementation detail, not something to rely on. Build the same values at runtime (e.g. via int() on a string) and that accidental sharing disappears, which is the version interviewers actually mean to test.
a = int("1000")
b = int("1000")
print(a is b) # False (built independently at runtime)
print(a == b) # True
small_a, small_b = int("100"), int("100")
print(small_a is small_b) # True (100 is in the cached -5..256 range)
Q. Why does changing backup also change cart?
Because backup = cart does not copy the list — it puts a second label on the same object. Any mutation through either name is visible through both. cart.copy() (or list(cart), or copy.copy(cart)) makes a genuinely separate object.
cart = ["rice"]
backup = cart
backup.append("dal")
print(cart) # ['rice', 'dal']
print(cart is backup) # True
real_copy = cart.copy()
real_copy.append("ghee")
print(cart) # ['rice', 'dal'] (unaffected)
print(real_copy) # ['rice', 'dal', 'ghee']
Q. What's wrong with def add_item(item, cart=[]):?
The default value [] is created once, when the function is defined — not once per call — so every call that doesn't pass its own cart shares and mutates that same list. The fix is to default to None and create a fresh list inside the function body.
def add_item(item, cart=[]):
cart.append(item)
return cart
print(add_item("pen")) # ['pen']
print(add_item("ink")) # ['pen', 'ink'] -- surprise, same list every call
def add_item_fixed(item, cart=None):
cart = [] if cart is None else cart
cart.append(item)
return cart
print(add_item_fixed("pen")) # ['pen']
print(add_item_fixed("ink")) # ['ink']
Q. How do // and % behave with negative numbers?
// is floor division — it rounds toward negative infinity, not toward zero — and % always returns a result with the same sign as the divisor. So -7 // 2 is -4 (not -3), and -7 % 2 is 1 (not -1), because -4 * 2 + 1 == -7 holds exactly.
print(7 // 2) # 3
print(-7 // 2) # -4
print(7 % 2) # 1
print(-7 % 2) # 1
print(7 / 2) # 3.5
Q. Why doesn't 0.1 + 0.2 == 0.3?
Floats are binary (base-2) approximations of decimal numbers, and 0.1 and 0.2 cannot be represented exactly in binary, so their sum carries tiny rounding error. Never compare floats with ==; use round() for display or math.isclose() for logic.
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False
import math
print(math.isclose(0.1 + 0.2, 0.3)) # True
Q. What does the else on a try block actually run?
It runs only if the try block completed with no exception — it does not run if an exception was caught. It exists to separate "code that might fail" from "code that should only run after success," which keeps the try block itself as small as possible. finally runs regardless, even if return fired inside try or except.
def safe_divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print("cannot divide by zero")
return None
else:
print("division succeeded")
return result
finally:
print("done trying")
print(safe_divide(10, 2))
# division succeeded
# done trying
# 5.0
print(safe_divide(10, 0))
# cannot divide by zero
# done trying
# None
Q. What does the else on a for/while loop mean?
It runs when the loop finishes without hitting a break. It's built for search loops: break as soon as you find what you want, and let else be the "not found" branch — no flag variable needed.
def find_first_even(nums):
for n in nums:
if n % 2 == 0:
print("found", n)
break
else:
print("no even number found")
find_first_even([1, 3, 5, 7]) # no even number found
find_first_even([1, 3, 4, 7]) # found 4
Q. EAFP vs LBYL — what's the difference, and which is more Pythonic?
LBYL ("look before you leap") checks a condition first, then acts (if key in d: ...). EAFP ("easier to ask forgiveness than permission") just acts and catches the failure (try: d[key] except KeyError: ...). Python favors EAFP: it's usually one lookup instead of two, and it avoids a race where the condition becomes false between the check and the use.
prices = {"apple": 30}
if "milk" in prices: # LBYL
print(prices["milk"])
else:
print("milk not priced yet (LBYL)")
try: # EAFP
print(prices["milk"])
except KeyError:
print("milk not priced yet (EAFP)")
# milk not priced yet (LBYL)
# milk not priced yet (EAFP)
Q. list vs tuple vs set vs dict — when do you reach for each?
list: an ordered, mutable sequence, use it as your default collection. tuple: ordered and immutable — use it for a fixed record (a coordinate, a row) or anything you need to hash (e.g. as a dict key). set: unordered, deduplicated, and O(1) membership checks — use it for "have I seen this?" and set algebra. dict: ordered-by-insertion key→value lookup — use it whenever you need to look something up by a name rather than a position.
cart_list = ["apple", "milk", "apple"]
cart_tuple = ("apple", "milk", "apple")
cart_set = {"apple", "milk", "apple"}
cart_dict = {"apple": 2, "milk": 1}
print(cart_list) # ['apple', 'milk', 'apple']
print(cart_tuple) # ('apple', 'milk', 'apple')
print(cart_set) # {'apple', 'milk'} (varies: set order isn't guaranteed)
print(cart_dict) # {'apple': 2, 'milk': 1}
try:
cart_tuple[0] = "bread"
except TypeError as e:
print(type(e).__name__, "-", e)
# TypeError - 'tuple' object does not support item assignment
Q. Explain the LEGB rule, and global vs nonlocal.
Name lookup goes Local → Enclosing → Global → Built-in, stopping at the first scope that has the name. Inside a function, a plain assignment creates a new local name by default; global tells Python to instead modify a module-level name, and nonlocal tells it to modify a name in an enclosing function's scope (the classic use is a closure that keeps a running count).
counter_total = 0
def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
counter = make_counter()
print(counter(), counter(), counter()) # 1 2 3
def show_global():
global counter_total
counter_total += 1
show_global()
print(counter_total) # 1
Q. What exactly do *args and **kwargs capture?
*args collects any extra positional arguments into a tuple; **kwargs collects any extra keyword arguments into a dict. They let a function accept a flexible, forward-compatible signature — common in decorators and logging wrappers that must pass through "whatever was called."
def order_summary(customer, *items, discount=0, **meta):
print("customer:", customer)
print("items:", items)
print("discount:", discount)
print("meta:", meta)
order_summary("Asha", "pen", "notebook", discount=10, city="Pune")
# customer: Asha
# items: ('pen', 'notebook')
# discount: 10
# meta: {'city': 'Pune'}
Revise with: Part 2 — Language fundamentals · Part 4 — Data structures · Part 5 — Functions · Part 6 — Errors and exceptions
Stage 2: Intermediate
Q. Shallow copy vs deep copy — what's the difference?
copy.copy() makes a new outer container but reuses the same inner objects — mutating a nested list through the copy still mutates the original. copy.deepcopy() recursively copies everything, so the two structures become fully independent. Plain assignment (=) copies neither; it's not even a shallow copy, it's an alias.
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
original[0].append(99)
print(original) # [[1, 2, 99], [3, 4]]
print(shallow) # [[1, 2, 99], [3, 4]] -- inner list is shared
print(deep) # [[1, 2], [3, 4]] -- fully independent
Q. What's wrong with [[0] * 3] * 3 as a 3x3 grid?
[x] * 3 repeats the same object three times, it doesn't make three independent copies. Since [0] * 3 builds one list, [[0] * 3] * 3 makes a grid where all three "rows" are references to that one list — writing to one row writes to all of them. Build each row with its own list comprehension instead.
grid = [[0] * 3] * 3
grid[0][0] = 1
print(grid) # [[1, 0, 0], [1, 0, 0], [1, 0, 0]] -- every row changed
fixed = [[0] * 3 for _ in range(3)]
fixed[0][0] = 1
print(fixed) # [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
Q. Why do all the lambdas in a loop return the same final value?
A closure captures the variable, not the value it held at the time the closure was created — this is late binding. By the time any of the lambdas actually run, the loop has finished and i holds its last value, so every lambda sees that same final i. Fix it by capturing the current value as a default argument, which is evaluated immediately at function-definition time.
makers = [lambda: i for i in range(3)]
print([m() for m in makers]) # [2, 2, 2]
fixed_makers = [lambda i=i: i for i in range(3)]
print([m() for m in fixed_makers]) # [0, 1, 2]
Q. What does a decorator actually do, and why does functools.wraps matter?
A decorator is a function that takes a function and returns a (usually wrapping) function, so @timer on greet is sugar for greet = timer(greet). Without functools.wraps, the returned wrapper replaces the original's __name__, __doc__, and signature with its own — breaking introspection, help(), and anything that inspects the function by name. @functools.wraps(func) copies that metadata onto wrapper.
import functools
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@timer
def greet(name):
"""Say hello."""
return f"Hello, {name}"
print(greet("Asha")) # Hello, Asha
print(greet.__name__) # greet -- would be 'wrapper' without @wraps
print(greet.__doc__) # Say hello.
Q. What happens if you iterate a generator twice?
A generator is a single-use iterator: once it's exhausted (every yield has fired and it has raised StopIteration), it stays exhausted — calling list() on it again gives an empty result, it does not restart. If you need to iterate more than once, either keep a fresh generator function to call again, or materialize it into a list once.
def numbers():
yield 1
yield 2
yield 3
gen = numbers()
print(list(gen)) # [1, 2, 3]
print(list(gen)) # [] -- already exhausted
Q. __str__ vs __repr__ — what's each one for?
__repr__ is for developers: unambiguous, ideally something you could paste back into Python to recreate the object; it's the fallback used everywhere (including inside containers like lists) if __str__ isn't defined. __str__ is for end users: a readable display form, used by print() and str(). Always define __repr__; define __str__ only if a nicer display form is worth the extra method.
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f"Point(x={self.x}, y={self.y})"
def __str__(self):
return f"({self.x}, {self.y})"
p = Point(3, 4)
print(p) # (3, 4) -- uses __str__
print(repr(p)) # Point(x=3, y=4) -- uses __repr__
print([p]) # [Point(x=3, y=4)] -- containers always use __repr__ on items
Q. How does Python resolve super().greet() when a class has two parents?
Python computes a single, consistent Method Resolution Order (MRO) for the whole class hierarchy using the C3 linearization algorithm, and super() walks one step along that order from the current class — not necessarily straight to the parent you'd expect. For diamond inheritance (Child(Left, Right), both from Base), the MRO visits Left then Right before Base, so Base is only reached once, no matter how many paths lead to it.
class Base:
def greet(self):
return "Base"
class Left(Base):
def greet(self):
return "Left->" + super().greet()
class Right(Base):
def greet(self):
return "Right->" + super().greet()
class Child(Left, Right):
pass
print(Child().greet()) # Left->Right->Base
print([c.__name__ for c in Child.__mro__]) # ['Child', 'Left', 'Right', 'Base', 'object']
Q. Why can't a list be a dict key or set member?
Sets and dicts use the key's hash() to find a bucket instantly, and that hash must stay valid for as long as the object sits in the container — which is impossible to guarantee for a mutable object, since mutating it after insertion would change its hash and corrupt the lookup. So Python makes mutable built-ins (list, dict, set) unhashable by design; immutable ones (tuple, str, int, frozenset) are hashable, provided everything inside them is too.
d = {("a", 1): "ok"}
print(d) # {('a', 1): 'ok'}
try:
bad = {[1, 2]: "nope"}
except TypeError as e:
print(type(e).__name__, "-", e)
# TypeError - cannot use 'list' as a dict key (unhashable type: 'list')
Q. What's the difference between @property, @staticmethod, and @classmethod?
@property turns a method into something read like a plain attribute (no parentheses), typically to compute or validate a value on the fly. @classmethod receives the class (cls) instead of an instance, mainly used for alternate constructors. @staticmethod receives neither self nor cls — it's just a plain function namespaced inside the class, for a helper that's related in theme but doesn't need instance or class state.
class Order:
tax_rate = 0.18
def __init__(self, amount):
self.amount = amount
@property
def total(self):
return self.amount * (1 + self.tax_rate)
@classmethod
def from_rupees_and_paise(cls, rupees, paise):
return cls(rupees + paise / 100)
@staticmethod
def is_valid_amount(amount):
return amount > 0
o = Order.from_rupees_and_paise(100, 50)
print(round(o.total, 2)) # 118.59
print(Order.is_valid_amount(-5)) # False
Q. ABC vs duck typing — how do they differ in what they enforce?
An abc.ABC with @abstractmethod makes a contract enforced at instantiation time: Python refuses to create an object of a subclass that hasn't implemented every abstract method. Duck typing enforces nothing — any object with a matching method just works, checked only when the call actually happens, which is faster to write but fails later (at the call site) rather than at the point of the mistake.
from abc import ABC, abstractmethod
class PaymentMethod(ABC):
@abstractmethod
def pay(self, amount): ...
class Upi(PaymentMethod):
def pay(self, amount):
return f"paid {amount} via UPI"
try:
PaymentMethod()
except TypeError as e:
print(type(e).__name__, "-", e)
# TypeError - Can't instantiate abstract class PaymentMethod without an implementation for abstract method 'pay'
class Wallet: # no shared base class at all
def pay(self, amount):
return f"paid {amount} via wallet"
def checkout(payer): # duck typing: anything with .pay() works
return payer.pay(99)
print(checkout(Upi())) # paid 99 via UPI
print(checkout(Wallet())) # paid 99 via wallet
Q. What does @dataclass generate for you, and what does frozen=True add?
@dataclass writes __init__, __repr__, and __eq__ (field-by-field) for you from the class's type-annotated attributes, so you stop hand-writing that boilerplate for plain data holders. frozen=True additionally blocks attribute assignment after construction (raising FrozenInstanceError) and makes the class hashable by default — useful for value objects you want to treat like immutable records.
from dataclasses import dataclass
@dataclass(frozen=True)
class Money:
amount: int
currency: str = "INR"
a, b = Money(100), Money(100)
print(a == b) # True -- generated __eq__ compares fields
print(a) # Money(amount=100, currency='INR')
try:
a.amount = 200
except Exception as e:
print(type(e).__name__, "-", e)
# FrozenInstanceError - cannot assign to field 'amount'
Q. What's a context manager, and how do you write your own?
A context manager defines __enter__ (run on entering with) and __exit__ (run on leaving, even if an exception occurred) — the pattern behind guaranteed cleanup like closing files or connections. contextlib.contextmanager lets you write one as a generator: code before yield is __enter__, code after (in a finally) is __exit__.
from contextlib import contextmanager
@contextmanager
def ledger_entry(name):
print(f"open {name}")
try:
yield name
finally:
print(f"close {name}")
with ledger_entry("invoice-1") as entry:
print("using", entry)
# open invoice-1
# using invoice-1
# close invoice-1
Q. Does a Python dict guarantee insertion order?
Yes — since Python 3.7, dict insertion order is a language guarantee, not an implementation detail (it used to just happen to be true in CPython 3.6). Iterating keys, values, or items always returns them in the order the keys were first inserted, which is why dicts are safe to use as an ordered mapping.
prices = {}
prices["milk"] = 55
prices["bread"] = 40
prices["apple"] = 30
print(list(prices.keys())) # ['milk', 'bread', 'apple']
Q. Are map() and filter() lazy? What happens if you consume the result twice?
Yes — both return a one-shot iterator, not a list, so no work happens until something actually pulls values from them (with list(), a for loop, etc.). Like a generator, once that iterator is exhausted, asking it for more just gives nothing back — it doesn't restart.
nums = [1, 2, 3, 4]
doubled = map(lambda n: n * 2, nums)
print(type(doubled).__name__) # map
print(list(doubled)) # [2, 4, 6, 8]
print(list(doubled)) # [] -- already consumed
Q. Are type hints enforced at runtime?
No. def final_price(price: float, ...) is pure documentation for humans and for static tools like mypy/pyright — calling final_price("1000", 10) is not blocked at the call site. The mismatch only surfaces later, as a normal runtime error, wherever the wrong type actually breaks an operation.
def final_price(price: float, discount: int = 10) -> float:
return price * (1 - discount / 100)
print(final_price("1000", 10))
# Traceback (most recent call last):
# ...
# TypeError: can't multiply sequence by non-int of type 'float'
Revise with: Part 9 — Object-oriented Python · Part 10 — Pythonic and functional Python · Part 11 — Testing and code quality
Stage 3: Advanced
Q. What is the GIL, and why doesn't adding threads speed up CPU-bound Python code?
The Global Interpreter Lock is a single lock in the standard (non free-threaded) CPython build that only lets one thread execute Python bytecode at a time. For CPU-bound work, threads take turns holding the GIL, so running the same total work across more threads doesn't parallelize it — it just adds scheduling overhead on top of the same serialized execution.
import threading, time
def cpu_bound(n):
total = 0
for i in range(n):
total += i * i
return total
def run_threads(n_threads, n):
threads = [threading.Thread(target=cpu_bound, args=(n,)) for _ in range(n_threads)]
start = time.perf_counter()
for t in threads: t.start()
for t in threads: t.join()
return time.perf_counter() - start
N = 3_000_000
print(f"1 thread, 1x work: {run_threads(1, N):.3f}s")
print(f"4 threads, 4x work: {run_threads(4, N):.3f}s")
# 1 thread, 1x work: 0.063s (varies)
# 4 threads, 4x work: 0.236s (varies) -- no 4x speed-up: the GIL serializes the CPU work
Q. threading vs multiprocessing vs asyncio — how do you choose?
Use threading (or asyncio) for I/O-bound work (network calls, file waits) — the GIL is released while waiting on I/O, so many waits overlap cheaply. Use multiprocessing / concurrent.futures.ProcessPoolExecutor for CPU-bound work — separate processes mean separate GILs, so you get real parallelism across cores. asyncio additionally needs every I/O call in the chain to be async-aware (await); it doesn't help a blocking call that doesn't cooperate. The free-threaded build (python3.14t) removes the GIL for threads doing CPU work, but it's officially supported, not the default, as of Python 3.14.
Q. What does __slots__ actually save, and what does it cost?
By default every instance keeps its attributes in a per-instance __dict__, which is flexible but has real overhead. __slots__ = (...) tells Python to allocate fixed slots for exactly those names instead, which is smaller and skips the dict — worthwhile for large numbers (100,000+) of small objects. The cost: instances can no longer take on new attributes that weren't declared in __slots__.
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
class SlimPoint:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x, self.y = x, y
p, s = Point(1, 2), SlimPoint(1, 2)
print(hasattr(p, "__dict__"), hasattr(s, "__dict__")) # True False
try:
s.z = 3
except AttributeError as e:
print(type(e).__name__, "-", e)
# AttributeError - 'SlimPoint' object has no attribute 'z' and no __dict__ for setting new attributes
Q. How does @property actually work under the hood?
property is a descriptor class: @property stores a property object in the class's __dict__, and reading instance.attr makes Python call that object's __get__(instance, owner), which runs your getter function. That's also why assigning wheel.area = 5 fails on a read-only property — the property object has a __set__ too (it just raises by default), and a descriptor with __set__ always wins over anything in the instance's own __dict__.
class Circle:
def __init__(self, radius):
self.radius = radius
@property
def area(self):
return round(3.14159 * self.radius ** 2, 2)
c = Circle(3)
prop = Circle.__dict__["area"]
print(type(prop).__name__) # property
print(prop.__get__(c, Circle)) # 28.27 -- what c.area does for you
print(c.area) # 28.27
Q. sys.getrefcount() returns one more than I expect — why?
CPython frees an object the instant its reference count hits zero. sys.getrefcount(obj) is accurate but passing obj to the function itself creates one extra, temporary reference for the duration of the call — so the number is always one higher than the "real" count of names/containers pointing at the object. Compare how the count changes, not its absolute value.
import sys
order = {"id": 101}
print(sys.getrefcount(order)) # 2 (the name `order` + the temporary call argument)
backup = order
print(sys.getrefcount(order)) # 3 (+1 for `backup`)
del backup
print(sys.getrefcount(order)) # 2 (back to the start)
Q. If reference counting frees objects instantly, why does Python still need a garbage collector?
Reference counting can't free a reference cycle — objects that point at each other (a.other = b; b.other = a) — because their counts never reach zero even when nothing outside the cycle can reach them. The cyclic garbage collector (gc module) runs periodically, finds such unreachable groups, and frees them. weakref sidesteps the whole problem: a weak reference points at an object without bumping its reference count, so it can't keep it alive or create a cycle.
import gc, weakref
class Node:
def __init__(self, name):
self.name, self.other = name, None
gc.disable()
a, b = Node("a"), Node("b")
a.other, b.other = b, a # a reference cycle
ref = weakref.ref(a)
del a, b
print(ref() is not None) # True -- still alive: the cycle keeps it going
print(gc.collect() > 0) # True -- the GC found and freed the cycle
print(ref() is not None) # False
gc.enable()
Q. How do you build a plugin registry without reaching for a metaclass?
__init_subclass__ is a classmethod hook that Python calls automatically every time a subclass is defined — perfect for self-registering plugins without touching the base class's code again. It's simpler and safer than a custom metaclass (which risks "metaclass conflict" errors when combined with other metaclasses) and is the first tool to reach for; use a metaclass only when you need to change how classes themselves are constructed.
class Plugin:
registry = {}
def __init_subclass__(cls, name, **kwargs):
super().__init_subclass__(**kwargs)
Plugin.registry[name] = cls
class CsvExporter(Plugin, name="csv"): pass
class JsonExporter(Plugin, name="json"): pass
print(list(Plugin.registry)) # ['csv', 'json']
print(Plugin.registry["json"] is JsonExporter) # True
Q. What does reading bytecode with dis actually show you?
dis.dis(func) disassembles a function's compiled bytecode into its stack-machine instructions — the literal steps the interpreter loop executes one at a time. It's useful for understanding why one piece of code is faster than another (fewer/simpler instructions usually wins) and for seeing the specializing adaptive interpreter (3.11+) pick faster typed variants of an instruction after a few repeated calls.
import dis
def add_gst(amount):
return amount * 1.18
dis.dis(add_gst)
Output (CPython 3.14.8 — exact instruction names can change between versions):
3 RESUME 0
4 LOAD_FAST_BORROW 0 (amount)
LOAD_CONST 0 (1.18)
BINARY_OP 5 (*)
RETURN_VALUE
Q. What problem does ExceptionGroup / except* solve?
Code that runs several independent operations (validating every field, awaiting several tasks) may hit more than one failure at once, and a single raise can only carry one exception. ExceptionGroup bundles multiple exceptions into one object you can still raise and catch; except* (Python 3.11+) catches and filters exceptions out of that group by type, running once per matching exception rather than stopping at the first one.
def validate(order):
errors = []
if order["qty"] <= 0:
errors.append(ValueError("qty must be positive"))
if order["price"] < 0:
errors.append(ValueError("price cannot be negative"))
if errors:
raise ExceptionGroup("invalid order", errors)
try:
validate({"qty": -1, "price": -5})
except* ValueError as eg:
for e in eg.exceptions:
print("caught:", e)
# caught: qty must be positive
# caught: price cannot be negative
Q. What does raise ... from ... do, and why use it?
It sets the new exception's __cause__ to the original exception, explicitly linking "this high-level error happened because of that low-level one" — so the traceback shows both, instead of silently losing the original cause when you translate a low-level exception into a more meaningful one for your caller.
def load_config(path):
try:
with open(path) as f:
return f.read()
except FileNotFoundError as e:
raise RuntimeError("config missing") from e
try:
load_config("does-not-exist.cfg")
except RuntimeError as e:
print(e) # config missing
print(type(e.__cause__).__name__) # FileNotFoundError
Q. How does structural (mapping/class) pattern matching with guards work?
match/case can destructure a dict by keys (case {"type": "ping"}) or an object by attributes, binding matched values to names in the same step — and an if clause after the pattern (a guard) adds an extra condition that must also hold for that case to fire. Cases are tried top to bottom, and the first one that matches (pattern and guard) wins.
def handle(event):
match event:
case {"type": "order_placed", "amount": amount} if amount > 1000:
return f"big order: {amount}"
case {"type": "order_placed", "amount": amount}:
return f"order: {amount}"
case {"type": "ping"}:
return "pong"
case _:
return "unknown"
print(handle({"type": "order_placed", "amount": 1500})) # big order: 1500
print(handle({"type": "order_placed", "amount": 200})) # order: 200
print(handle({"type": "ping"})) # pong
Q. What are "immortal objects", and why does sys.getrefcount(None) look insane?
Since CPython 3.12, a handful of objects that are effectively never collected — None, True, False, and small cached integers — are marked immortal: their refcount is pinned so it's never incremented or decremented at all. That's why sys.getrefcount(None) returns an enormous, fixed-looking number rather than "however many names point at None right now" — it's not counting references at all for these objects.
import sys
print(sys.getrefcount(None) > 1_000_000) # True
print(sys.getrefcount(True) > 1_000_000) # True
Q. How do you find which function is actually slow, and what do tottime/cumtime mean?
Measure first with cProfile, which records every function call; pstats.Stats(...).sort_stats("cumulative") then ranks them. tottime is time spent inside that function only, excluding functions it calls; cumtime is that function plus everything it calls. Read top-down by cumtime until you hit the first function you wrote with a large value, then look at what it calls with a large tottime — that's the real cost to fix.
import cProfile, pstats
def slow_repeat_check(names):
seen, repeats = [], []
for name in names:
if name in seen and name not in repeats:
repeats.append(name)
seen.append(name)
return sorted(repeats)
def job():
return slow_repeat_check(["asha", "ravi", "asha", "meera"] * 2000)
profiler = cProfile.Profile()
profiler.enable()
job()
profiler.disable()
pstats.Stats(profiler).strip_dirs().sort_stats("cumulative").print_stats(3)
Output (varies):
8007 function calls in 0.001 seconds
Ordered by: cumulative time
List reduced from 5 to 3 due to restriction <3>
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.001 0.001 s3_profile.py:13(job)
1 0.001 0.001 0.001 0.001 s3_profile.py:5(slow_repeat_check)
8003 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}
Q. Protocol vs ABC in advanced typing — what's the difference?
Both describe "an object that supports these methods," but ABC is nominal — a class must explicitly inherit from it (and implement the abstract methods) to count — and that's checked at instantiation. Protocol is structural — any object with matching method signatures satisfies it, with no inheritance needed at all, and it's primarily a static-typing tool: a type checker verifies it, but isinstance() only works on it at runtime if it's decorated @runtime_checkable.
from typing import Protocol
class Discountable(Protocol):
def discount(self) -> float: ...
class Coupon: # never mentions Discountable
def discount(self) -> float:
return 0.1
def apply(item: Discountable) -> float:
return 100 * (1 - item.discount())
print(apply(Coupon())) # 90.0 -- structural typing just works
print(isinstance(Coupon(), Discountable))
# Traceback (most recent call last):
# ...
# TypeError: Instance and class checks can only be used with @runtime_checkable protocols
Q. What changed with free-threaded Python, and should you use it by default?
Python 3.13 shipped an experimental free-threaded build (no GIL); Python 3.14 made it officially supported — real multi-core parallelism for CPU-bound threads, without switching to multiprocessing. It is still not the default build you get from python.org or most package managers, C-extension ecosystem support is still catching up, and single-threaded code can run somewhat slower on it. Reach for it deliberately (python3.14t), after measuring, not as a blanket default.
Revise with: Part 13 — Concurrency · Part 14 — Python internals · Part 15 — Advanced typing and errors
Stage 4: DSA in Python
Q. Why is x in some_set so much faster than x in some_list?
A list membership check is a linear scan, worst case O(n). A set (and a dict's keys) use hashing to jump straight to the right bucket, O(1) on average, regardless of size. If you're doing repeated "have I seen this?" checks, build the set once outside the loop.
import timeit
setup = "ids = list(range(20_000)); id_set = set(ids)"
list_time = timeit.timeit("19_999 in ids", setup=setup, number=2_000)
set_time = timeit.timeit("19_999 in id_set", setup=setup, number=2_000)
print(f"list: {list_time:.4f}s set: {set_time:.6f}s") # list: 0.1898s set: 0.000021s (varies)
print(set_time < list_time) # True
Q. Why is list.pop(0) or list.insert(0, x) a performance trap in a loop?
Both have to shift every remaining element down or up by one slot, so each call is O(n) — doing that in a loop makes the whole job O(n²). collections.deque is a doubly-linked structure with O(1) operations at both ends (popleft(), appendleft()), which is the right tool for a queue, a sliding window, or bounded history.
from collections import deque
history = deque(maxlen=3)
for page in ["home", "search", "cart", "checkout"]:
history.append(page)
print(list(history)) # ['search', 'cart', 'checkout'] -- oldest dropped automatically
q = deque([1, 2, 3])
q.appendleft(0)
print(q.popleft()) # 0
print(q) # deque([1, 2, 3])
Q. What's the two-pointer technique, and what kind of problem calls for it?
Walk two indices toward each other (or together) across a sorted sequence, narrowing the search space each step instead of checking every pair — turning an O(n²) brute-force pair search into O(n). Classic use: "find a pair that sums to a target" in a sorted array.
def has_pair_with_sum(sorted_nums, target):
left, right = 0, len(sorted_nums) - 1
while left < right:
total = sorted_nums[left] + sorted_nums[right]
if total == target:
return (sorted_nums[left], sorted_nums[right])
if total < target:
left += 1
else:
right -= 1
return None
print(has_pair_with_sum([1, 3, 4, 7, 11], 11)) # (4, 7)
print(has_pair_with_sum([1, 3, 4, 7, 11], 20)) # None
Q. What's the sliding window technique?
Keep a running window of a fixed (or growing/shrinking) size over a sequence, updating a running total incrementally as the window moves instead of recomputing it from scratch each time — turning an O(n*k) "best window of size k" scan into O(n).
def best_window_sum(sales, k):
window_sum = sum(sales[:k])
best = window_sum
for i in range(k, len(sales)):
window_sum += sales[i] - sales[i - k]
best = max(best, window_sum)
return best
sales = [200, 150, 400, 100, 500, 300]
print(best_window_sum(sales, 3)) # 1000 -- best 3-day total
Q. What's the go-to tool for "count occurrences" problems?
collections.Counter — a dict subclass built exactly for counting hashable items, with .most_common(n) for ranking straight out of the box. It's almost always simpler and faster than hand-rolling a dict with .get(key, 0) + 1.
from collections import Counter
orders = ["pen", "ink", "pen", "pen", "notebook", "ink"]
counts = Counter(orders)
print(counts) # Counter({'pen': 3, 'ink': 2, 'notebook': 1})
print(counts.most_common(2)) # [('pen', 3), ('ink', 2)]
Q. How would you check balanced brackets, and why is a stack the right structure?
Push every opening bracket; on a closing bracket, it must match whatever opening bracket was pushed most recently — which is exactly "last in, first out," i.e. a stack. A plain Python list with .append()/.pop() is already a perfectly good stack.
def is_balanced(expr):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in expr:
if ch in "([{":
stack.append(ch)
elif ch in ")]}":
if not stack or stack.pop() != pairs[ch]:
return False
return not stack
print(is_balanced("(a[b]{c})")) # True
print(is_balanced("(a[b)")) # False
Q. BFS vs DFS — when do you use each, and how do you implement BFS in Python?
BFS explores level by level using a queue, and is the right choice whenever you need the shortest path in an unweighted graph (fewest hops). DFS explores as deep as possible before backtracking, using a stack (or plain recursion, which uses the call stack for you) — better for "does a path exist" or exhaustive search like backtracking, where shortest-path isn't the goal.
from collections import deque
def bfs_order(graph, start):
seen = {start}
order = []
queue = deque([start])
while queue:
node = queue.popleft()
order.append(node)
for neighbour in graph[node]:
if neighbour not in seen:
seen.add(neighbour)
queue.append(neighbour)
return order
graph = {"a": ["b", "c"], "b": ["d"], "c": ["d"], "d": []}
print(bfs_order(graph, "a")) # ['a', 'b', 'c', 'd']
Q. How do you binary search without writing the loop yourself?
bisect.bisect_left/bisect_right find the insertion point that keeps a sorted sequence sorted, in O(log n) — the building block for "which band does this value fall into," ranking, and dedup-insert, without hand-writing the low/high/mid loop.
import bisect
price_bands = [0, 500, 1000, 5000, 10000]
labels = ["free", "budget", "mid", "premium", "luxury"]
def band_for(price):
idx = bisect.bisect_right(price_bands, price) - 1
return labels[idx]
print(band_for(750)) # budget
print(band_for(10)) # free
print(band_for(10000)) # luxury
Q. How do you solve a "top-k" problem efficiently, and what does heapq give you?
Keep a min-heap of size k: push every new item, and whenever the heap grows past k, pop the smallest — whatever survives is the k largest, in O(n log k) instead of sorting everything in O(n log n). heapq.nlargest(k, iterable, key=...) does exactly this for you when k is small relative to the data.
import heapq
posts = [("post-a", 120), ("post-b", 980), ("post-c", 450), ("post-d", 999), ("post-e", 10)]
print(heapq.nlargest(3, posts, key=lambda p: p[1]))
# [('post-d', 999), ('post-b', 980), ('post-c', 450)]
heap = []
for name, views in posts:
heapq.heappush(heap, (views, name))
if len(heap) > 3:
heapq.heappop(heap)
print(sorted(heap, reverse=True))
# [(999, 'post-d'), (980, 'post-b'), (450, 'post-c')]
Q. How does functools.lru_cache turn plain recursion into dynamic programming?
Naive recursive solutions (like coin change) recompute the same sub-problem exponentially many times. @lru_cache memoizes: the first call for a given set of arguments computes and stores the result, every later call with the same arguments returns the cached value instantly — turning exponential recursion into one call per distinct sub-problem, with zero changes to the recursive logic itself.
from functools import lru_cache
@lru_cache(maxsize=None)
def fewest_coins(amount, coins=(1, 2, 5)):
if amount == 0:
return 0
if amount < 0:
return float("inf")
return 1 + min(fewest_coins(amount - c, coins) for c in coins)
print(fewest_coins(11)) # 3 (5 + 5 + 1)
print(fewest_coins.cache_info())
# CacheInfo(hits=18, misses=16, maxsize=None, currsize=16)
Q. A custom linked list vs a Python list — why would you ever hand-roll one?
Python's list is a dynamic array: O(1) random access by index but O(n) to insert/delete at the front or middle. A linked list gives O(1) insertion/deletion at a known node (no shifting) at the cost of O(n) random access and extra memory per node for the pointer — which is exactly why it's mostly an interview/teaching structure in Python: deque already covers the common "fast at both ends" need without hand-rolled nodes.
Q. Is Python's built-in sort stable — does that matter?
Yes — sorted()/list.sort() use Timsort, which is stable: items that compare equal keep their original relative order. That matters whenever you sort by one key but want a meaningful tiebreak order preserved, e.g. sort by score, and students with the same score should stay in whatever order they were already in (alphabetical, arrival order, etc.) without sorting by a second key explicitly.
students = [("Ravi", 80), ("Asha", 92), ("Meera", 80), ("Dev", 92)]
by_score_desc = sorted(students, key=lambda s: s[1], reverse=True)
print(by_score_desc)
# [('Asha', 92), ('Dev', 92), ('Ravi', 80), ('Meera', 80)]
Revise with: Part 17 — Data structures and algorithms in Python
Stage 5: Specialization
These are talking points, not code — Stage 5 is "pick one track," so an interviewer will go only as deep as the track on your resume. Speak to the trade-off, not library trivia.
Q. What does a validation layer like Pydantic buy you over plain dicts in a web backend?
A plain dict trusts whatever JSON the client sent — a missing or wrong-typed field blows up deep inside your business logic, far from where the bad data entered. A typed model validates and coerces the data at the boundary, so by the time your handler code runs, it can trust the shape it received; errors come back immediately, as a clear 422-style response, not a mystery KeyError three functions later.
Q. Why can an async def endpoint hurt performance if it calls a blocking function inside it?
asyncio gets its concurrency by cooperatively yielding control at await points — if the code inside an async handler calls a blocking operation (synchronous file I/O, a non-async DB driver, time.sleep), it holds up the entire event loop for everyone else, since nothing yields. The whole benefit of async depends on every I/O call in the chain actually being async-aware.
Q. What's the N+1 query problem, and why does it show up with ORMs?
It's loading a list of N parent records with one query, then triggering one additional query per item to fetch a related field (e.g. each order's customer), for N+1 total database round trips instead of 2. ORMs make this easy to write by accident because the related-object access looks like a free attribute lookup; the fix is to eagerly join or batch-load the relation up front.
Q. pandas vs NumPy — when do you reach for which?
NumPy is the array library: homogeneous, fixed-type numeric arrays and fast vectorized math, with no notion of column names or mixed types. pandas is built on top of NumPy and adds labeled rows/columns, heterogeneous column types, and the data-wrangling operations (filtering, groupby, joins) that raw NumPy doesn't give you — reach for pandas when the data has structure and labels worth tracking, NumPy when it's pure numerical computation.
Q. Why is a "vectorized" pandas operation faster than looping over rows in Python?
A Python-level loop over rows pays per-row interpreter overhead for every single element. A vectorized operation (df["total"] = df["price"] * df["qty"]) pushes the whole column-wise operation down into compiled, C-level loops operating on contiguous memory — one call instead of millions of small ones, the same idea as "built-ins beat hand-written loops" from Stage 3's internals discussion.
Q. Why split data into train and test sets, and what does overfitting mean?
A model evaluated on the same data it learned from will look artificially good — it may have memorized quirks of that specific data rather than learned a pattern that generalizes. Holding out a test set it never sees during training gives an honest read on how it performs on new data; overfitting is exactly the failure mode where training performance is high but test performance is much lower, because the model learned the noise, not the signal.
Q. What's the one-sentence idea behind RAG, and why do you still need to evaluate it?
Retrieval-augmented generation looks up relevant snippets from your own documents first, then feeds those snippets to the model alongside the question, so answers are grounded in your data instead of only the model's training knowledge. You still evaluate it because retrieval can return the wrong or incomplete snippets, and the model can still misread or hallucinate on top of correct context — "it's grounded" doesn't automatically mean "it's correct."
Q. Why does a scheduled scraping or automation script need to be idempotent?
Scheduled jobs get retried — by a cron overlap, a crash-and-restart, a manual rerun — and a non-idempotent job (one that assumes "this runs exactly once") can double-write rows, double-send notifications, or corrupt a file on a second run. Designing for idempotency (checking what's already been done, upserting instead of blindly inserting, naming outputs by a stable key) means a rerun is safe, not just "normally fine."
Revise with: Stage 5 overview · Web backend track · Data analytics track · ML / AI track · Automation track