Python Programming Questions
Python as an interview language: core syntax, data types and built-in collections, comprehensions, iterators and generators, idiomatic style, and the standard library, extending into data-oriented and automation use of the language and its common libraries. Covers writing correct, Pythonic code and reasoning about the language's semantics. The most heavily exercised language surface in this category across engineering and data roles.
For an in-memory dataset you're processing repeatedly, compare storing it as a list of dicts (row-oriented) versus a dict of lists or tuple-of-arrays (column-oriented). What changes about memory layout, CPU cache behavior, and which operations get faster or slower?
Sample Answer
Direct answer
A list of dicts (row-oriented) stores each record as its own independent Python object, scattered across the heap and reached through pointers; a dict of lists or tuple-of-arrays (column-oriented) stores each field as one contiguous run of values. Row-oriented layout is convenient when you read or write whole records at once and the schema varies row to row; column-oriented layout is dramatically faster and more memory-compact for operations that touch one field across many rows, because a contiguous, uniformly-typed buffer lets tools like numpy operate on it in tight, cache-friendly C loops instead of chasing a pointer through a fresh Python object for every row.
Structured elaboration
Memory layout: in a list of dicts, each row is a full dict object (with its own internal hash table for a handful of keys) plus a separate small object for each field value; the list itself only holds pointers to these scattered dict objects. In a dict of lists, each column is one Python list whose elements still are individual boxed objects (still scattered, just grouped by field instead of by row), while a numpy array goes further and stores raw, unboxed values contiguously, with no per-element Python object at all.
CPU cache behavior: processing "one field across every row" in a list of dicts means following a different pointer for every row (poor spatial locality: each dict lives at an unrelated heap address, so the CPU's cache line brought in for one row's dict is unlikely to help with the next row) plus a hash lookup per field access. A numpy column is one contiguous buffer, so scanning it sequentially reads mostly-adjacent memory, which is exactly the access pattern CPU caches are built to reward, and it enables SIMD-style, C-level loops (SIMD: Single Instruction, Multiple Data, a CPU feature that applies one instruction to several values in a single step instead of one at a time; numpy's vectorized operations) instead of a Python-level loop with interpreter overhead on every element.
Which operations get faster or slower:
| Operation | Row-oriented (list of dicts) | Column-oriented (numpy) |
|---|---|---|
| Aggregate/transform one field across all rows | Slow: one pointer chase and hash lookup per row | Fast: one contiguous, cache-friendly, vectorized pass |
| Read or write one whole record | Fast: one object holds every field together | Slower: touches a separate array per field |
| Insert or delete a single record | O(1) amortized (list.append) | O(n) per column (array insert/delete) |
| Heterogeneous, per-row-varying schema | Natural fit | Needs padding or a fallback structure |
Worked example
Same aggregation (sum(price * qty)), computed three ways on 50,000 rows, verified on CPython 3.12 to confirm all three agree exactly before comparing their memory profile:
import sys
import numpy as np
N = 50_000
rows = [{"price": float(i), "qty": i % 7} for i in range(N)] # row-oriented
cols_list = {"price": [float(i) for i in range(N)], "qty": [i % 7 for i in range(N)]} # column-oriented, plain lists
cols_np = {"price": np.arange(N, dtype="f8"), "qty": (np.arange(N) % 7)} # column-oriented, numpy
total_row = sum(r["price"] * r["qty"] for r in rows)
total_col_list = sum(p * q for p, q in zip(cols_list["price"], cols_list["qty"]))
total_col_np = float(np.sum(cols_np["price"] * cols_np["qty"]))
assert total_row == total_col_list
assert abs(total_row - total_col_np) < 1e-6
All three report 3749975004.0. The memory picture behind that identical result is not identical at all:
print(sys.getsizeof(rows[0])) # 184: per-row dict shell alone, excludes key/value objects
print(cols_np["price"].nbytes / N) # 8.0 bytes/element, contiguous
print(cols_np["qty"].nbytes / N) # 8.0 bytes/element, contiguous
Every row's dict shell alone costs 184 bytes before counting a single stored value, while the entire price or qty column packs into exactly 8 bytes per element, matching a raw C double/int64 with no extra per-value overhead at all.
Trade-offs & pitfalls
- Row-oriented storage is the right default for heterogeneous, semi-structured records (each row can have a different set of fields) or workloads that mostly touch whole records at a time (an OLTP-style, online-transaction-processing pattern of single-record reads and writes); forcing such data into a rigid columnar shape adds friction for no analytical benefit.
- Column-oriented storage assumes a fixed, uniform schema; a sparse or highly variable-shape dataset needs either a hybrid design (a dense columnar core plus a fallback dict for exceptions) or accepts padding with a sentinel/NaN value for missing fields.
- Converting a large list-of-dicts into a columnar representation is itself an O(n) pass with real allocation cost; doing this conversion repeatedly inside a hot loop (rather than once, at the pipeline's ingestion boundary) throws away the benefit it is meant to provide.
- A plain "dict of lists" is columnar in shape but not in memory: unlike a numpy array, its elements are still individually-boxed Python objects scattered on the heap, so it gets the API convenience of column-wise iteration without the cache-locality or memory-compactness benefit; the win from true contiguous storage only shows up once you move to
numpy(or a similar typed, packed buffer). - For large datasets, exporting the columnar in-memory representation to a columnar on-disk format (Parquet, a compressed, column-oriented file format for tabular data, storing each column's values contiguously on disk the same way this section's in-memory columnar layout does) at pipeline boundaries compounds the benefit further (compression exploits column-wise value repetition much better than row-wise), but that is a persistence decision, separate from the in-memory layout choice this question is about.
Implement a thread-safe LRU cache decorator in Python without using functools.lru_cache (you may use threading primitives). The decorator should accept a maxsize and be safe for concurrent access by multiple threads. Discuss complexity and potential contention points.
Sample Answer
Approach: implement LRU with a dict for storage and a doubly-linked list for order; use threading.RLock (a lock that the SAME thread can safely acquire again without deadlocking itself, unlike a plain threading.Lock, in case the cache logic ever needs to re-enter the lock while already holding it) for concurrency. Decorator returns wrapper that locks around lookups and updates, minimizing lock hold time.
Implementation:
import threading
from functools import wraps
def lru_cache(maxsize=128):
def deco(func):
cache = {}
head = tail = None
lock = threading.RLock()
class Node:
__slots__=('key','val','prev','next')
def __init__(self,k,v):
self.key=k;self.val=v;self.prev=self.next=None
def _move_to_front(node):
nonlocal head, tail
if node is head:
return # already the most-recently-used entry, nothing to do
# unlink node from wherever it currently sits
if node.prev:
node.prev.next = node.next
if node.next:
node.next.prev = node.prev
if node is tail:
tail = node.prev
# relink it at the head (the most-recently-used end)
node.prev = None
node.next = head
if head:
head.prev = node
head = node
if tail is None:
tail = node
@wraps(func)
def wrapper(*args, **kwargs):
nonlocal head, tail # wrapper reassigns both below on eviction; without
# this declaration LEGB makes them locals instead
key=(args,tuple(sorted(kwargs.items())))
with lock:
node=cache.get(key)
if node:
_move_to_front(node); return node.val
val=func(*args, **kwargs)
with lock:
if key in cache: return cache[key].val
node=Node(key,val); cache[key]=node; _move_to_front(node)
if len(cache)>maxsize:
# cache is over capacity: evict the true tail, the
# least-recently-used entry, from both the linked list
# and the dict
lru_node = tail
tail = lru_node.prev
if tail:
tail.next = None
else:
head = None
del cache[lru_node.key]
return val
return wrapper
return deco
Worked example: verified on CPython 3.12, calling the decorated function through a full eviction cycle so the policy can actually be watched working, not just taken on faith.
calls = []
@lru_cache(maxsize=2)
def square(n):
calls.append(n)
return n * n
print(square(1)) # 1 (miss: cache empty, computed and cached; order (MRU->LRU): [1])
print(square(2)) # 4 (miss: computed and cached; order: [2, 1])
print(square(1)) # 1 (hit: served from cache, 1 moves back to the front; order: [1, 2])
print(square(3)) # 9 (miss: cache was full at {1, 2}; since 1 was just reused, 2 is now
# the least-recently-used entry and gets evicted to make room for 3; order: [3, 1])
print(square(2)) # 4 (miss again: 2 was evicted in the previous step, so this recomputes
# instead of hitting the cache; order: [2, 3])
print(calls) # [1, 2, 3, 2] -- 2 appears twice: proof it was actually evicted and
# had to be recomputed, not just a claim
Complexity: O(1) average get/set.
Contention: a single global lock, one shared threading.RLock protecting the whole cache, serializes cache access: only one thread at a time can even check whether something is cached, regardless of which key it wants, which becomes a bottleneck under heavy concurrent traffic. Two ways to reduce that: a read-mostly optimistic check (read the dict for a hit without taking the lock first, since a plain dict read is safe to race on for a snapshot lookup, and only take the lock to confirm the hit and update the linked-list ordering, so the common cache-hit path spends less time holding the lock), or shard locks (split one cache into several smaller caches, each with its own separate lock, and route each key to one shard by hashing it, e.g. shard = hash(key) % num_shards; two threads reading keys that land in different shards no longer contend for the same lock at all, at the cost of maxsize now being enforced per shard rather than globally).
Write a decorator that works both as @retry (no parentheses) and as @retry(max_attempts=5) (called with arguments). What makes this ambiguous case hard, and how do you detect which form was used?
Sample Answer
Direct answer
Give the decorator function an optional first positional parameter (conventionally func=None) alongside keyword-only configuration parameters. When Python evaluates @retry with no parentheses, it calls retry(the_function) directly, so func arrives as the function itself. When Python evaluates @retry(max_attempts=5), it first calls retry(max_attempts=5) with func left at its default of None, and that call must return the actual decorator, which Python then applies to the function on the next line. The whole trick is: check whether func is None and either apply the wrapping immediately or hand back a configured decorator to be applied a moment later.
Structured elaboration
What makes this genuinely ambiguous is that @retry and @retry(max_attempts=5) invoke the same name in two structurally different ways, and Python gives you no explicit signal about which form was used; the only observable difference is what got passed as the first argument:
- No-parens form (
@retry): Python evaluatesretryas an expression, then immediately calls it with the decorated function as the sole argument:retry(some_function). Here,funcis bound to a real callable. - Parens form (
@retry(max_attempts=5)): Python first callsretry(max_attempts=5)to produce a value, then applies that value as the decorator to the function on the next line, calling that value with the function. Here,funcis not supplied at all (or would only be supplied asNoneby default), and the whole first call must return something else that is itself callable and ready to receive the function.
So the detection is: is the value bound to func a callable function (no-parens case), or is it the default None (parens case, meaning we're still waiting for both the config and the function)? Concretely:
- If
func is None: this is the parenthesized call. Return the innerdecoratorfunction, which Python will apply to the actual function next. - If
funcis notNone: this is the no-parens call,funcalready is the function to wrap. Applydecorator(func)immediately and return the wrapped result.
functools.wraps is orthogonal to the ambiguity itself but is required either way, without it, the wrapped function's __name__, __doc__, and other metadata would silently become the wrapper's instead of the original function's, which breaks introspection, debugging, and tools that key off __name__.
Worked example
import functools
from typing import Callable, Optional
def retry(func: Optional[Callable] = None, *, max_attempts: int = 3):
def decorator(fn: Callable):
@functools.wraps(fn)
def wrapped(*args, **kwargs):
attempts = 0
while True:
try:
return fn(*args, **kwargs)
except Exception:
attempts += 1
if attempts >= max_attempts:
raise
return wrapped
if func is None:
return decorator # parens form: still need the function
return decorator(func) # no-parens form: func is already the function
calls = {"a": 0, "b": 0}
@retry
def flaky_a():
calls["a"] += 1
if calls["a"] < 2:
raise ValueError("boom")
return "a-ok"
@retry(max_attempts=5)
def flaky_b():
calls["b"] += 1
if calls["b"] < 4:
raise ValueError("boom")
return "b-ok"
print(flaky_a(), calls["a"]) # a-ok 2
print(flaky_b(), calls["b"]) # b-ok 4
print(flaky_a.__name__) # flaky_a (functools.wraps preserved the name)
flaky_a succeeds on its second internal call (default max_attempts=3 is enough); flaky_b needed 4 internal calls, only reachable because max_attempts=5 was configured through the parens form.
Trade-offs & pitfalls
- The keyword-only
*beforemax_attemptsis load-bearing, not stylistic. Without it,retry(5)(a bare positional call) would ambiguously try to bind5tofunc, which is nonsensical; keyword-only parameters force all configuration to be named, so the only wayfuncgets a non-Nonevalue is through the actual no-parens decoration path. - This pattern does not extend to
async deffunctions for free. Thewrappedfunction here callsfn(*args, **kwargs)synchronously; wrapping anasync defwith this decorator would return a coroutine object without awaiting it, silently swallowing the retry logic. An async-aware version needs anasync def wrappedthatawaitsfn(...), and ideally detection of which kind of function it's wrapping (inspect.iscoroutinefunction). - Retrying on bare
Exceptionis intentionally broad here for brevity but is a common wrong turn in production code: it will retry on bugs (aTypeErrorfrom a coding mistake) exactly as eagerly as on transient failures (a network timeout), masking real errors behind a few extra silent attempts. A production version should accept an explicit tuple of exception types to retry on. - No backoff between attempts means a fast-failing dependency gets hammered immediately on every retry; production retry decorators almost always add a delay (ideally with jitter) between attempts.
What does if __name__ == '__main__': actually do in Python? Show a small script that behaves differently when run directly versus imported as a module, and give a real reason you'd use this idiom.
Sample Answer
Direct answer
Every module has a variable named __name__ that Python sets automatically. When a file is run directly (python script.py), Python sets that file's __name__ to the string "__main__". When the same file is instead imported by another module, __name__ is set to the module's own name (its filename, without .py) instead. The idiom if __name__ == "__main__": lets a single file define reusable functions and also double as a runnable script, without the "run as a script" code executing a second time whenever something else imports it.
Structured elaboration
Why this matters: every top-level statement in a module runs once, immediately, the instant the module is first imported or run, not lazily on first use. Any code sitting outside a function, and outside the __name__ guard, always executes on import whether that was intended or not.
The real reasons to reach for it: a module holds both library functions and a demo or command-line interface (CLI) entry point in the same file, or a script that a test suite imports (to reach one function inside it) must not also re-run its "main" logic just because it was imported rather than executed.
Worked example
Verified on CPython 3.12. script_a.py:
def preprocess(data):
'''Lowercase every string in data.'''
return [s.lower() for s in data]
def _demo():
sample = ["Hello", "WORLD"]
print("Preprocessed:", preprocess(sample))
print("module __name__ is:", __name__)
if __name__ == "__main__":
_demo()
Running it directly:
$ python script_a.py
module __name__ is: __main__
Preprocessed: ['hello', 'world']
Importing it from elsewhere instead:
import script_a
print(script_a.preprocess(["Hi"]))
module __name__ is: script_a
['hi']
The print("module __name__ is: ...") line, sitting outside any function and outside the guard, runs in both cases (verified: it prints in both the direct-run and the import case, only with a different value each time); _demo() runs only in the direct-run case, verified above.
Trade-offs & pitfalls
- Common wrong turn: putting expensive top-level work (loading a large model, opening a database connection, reading a large file) directly at module level, outside any function and outside the
__name__guard. That cost is paid on every import, including in contexts that never intended to run it, a test suite, a REPL session, or another script importing just one helper function. - The guard only protects the code inside its own
ifblock; a stray statement at true module level, outside every function and outside the guard, still executes on import regardless, the guard does not retroactively protect the rest of the file. - A common structure for CLIs keeps parsing and dispatch inside an ordinary function (
def main(): ...) and reduces the guard to a single call,if __name__ == "__main__": main(), so the logic itself stays importable and unit-testable as a plain function, separate from the decision to run it right now.
You have CPU-bound preprocessing that's become a bottleneck in a Python pipeline. Walk through your decision process: threading, multiprocessing, or asyncio, and why. Then say how your answer changes if the bottleneck were I/O-bound instead (say, many blocking network calls) and you needed to run them concurrently without a full rewrite.
Sample Answer
Direct answer
For CPU-bound preprocessing, reach for multiprocessing, not threading or asyncio. CPython threads are still limited by the GIL (Global Interpreter Lock, the mutex that lets only one thread execute Python bytecode at a time), so extra threads do not add parallel CPU throughput for pure-Python work. Multiple processes each get their own interpreter and GIL, so they genuinely run on separate cores. If the bottleneck were I/O-bound instead (many blocking network calls), the calculus flips: threading or asyncio both work because I/O releases the GIL while waiting, and if you cannot afford to rewrite the code as async, wrapping the existing blocking calls in a thread pool gets you concurrency without touching the call sites.
Structured elaboration
Decision framework
| Bottleneck | Best fit | Why | Rewrite cost |
|---|---|---|---|
| CPU-bound (pure Python loops, parsing, transforms) | multiprocessing | Bypasses the GIL, uses multiple cores | Moderate: must be picklable, watch memory duplication |
| CPU-bound, but hot path is numpy/C extension | Threads can help | Many numpy/BLAS (Basic Linear Algebra Subprogram) operations release the GIL internally during the C computation | Low |
| I/O-bound (network, disk, DB calls), full control of the code | asyncio | Cooperative concurrency, single thread, no GIL contention, scales to thousands of concurrent waits | High: every call in the chain must be async-compatible |
| I/O-bound, existing blocking/sync code you cannot fully rewrite | Thread pool (concurrent.futures.ThreadPoolExecutor) or asyncio.to_thread | Blocking I/O releases the GIL while waiting, so threads overlap waits even though only one runs Python bytecode at a time | Low: wrap existing calls, no async rewrite |
Why threading fails for CPU work but multiprocessing does not: the GIL only needs to be released while native code is running outside the interpreter loop, or while a thread is blocked in a system call. A tight Python loop doing arithmetic never leaves the interpreter, so the GIL is essentially held the whole time; other threads make no CPU progress. A separate process has its own interpreter and its own GIL, so N processes can use N cores concurrently.
Why asyncio does not help the CPU case: asyncio is single-threaded cooperative multitasking. It only reclaims time that would otherwise be spent idly waiting (on a socket, a file descriptor, a timer). A CPU-bound loop never yields control back to the event loop, so it blocks every other coroutine until it finishes; you get zero parallelism.
Migrating the I/O-bound half without a full rewrite: if you have synchronous code (e.g. calls to a blocking HTTP client or database driver) and cannot convert every layer to async def/await, you do not have to. Two low-effort options:
- Run the existing blocking calls in a thread pool via
concurrent.futures.ThreadPoolExecutor, and drive them concurrently with.submit()/as_completed(), noasynckeyword anywhere. - If you already have an asyncio event loop elsewhere in the program and want to call into old blocking code from it, use
asyncio.to_thread(blocking_fn, *args), which offloads the blocking call to a worker thread and awaits the result, letting the rest of your code stay synchronous.
Worked example
CPU-bound case, ProcessPoolExecutor applying a preprocessing function to large numpy arrays via a memory-mapped file so workers do not each need a private in-memory copy of the whole array (verified on CPython 3.12, seeded so the output is reproducible):
import numpy as np
from concurrent.futures import ProcessPoolExecutor, as_completed
import os
INPUT_PATH, OUTPUT_PATH = "input.dat", "output.dat"
DTYPE, SHAPE, CHUNK_SIZE = np.float32, (1_000_000,), 200_000
_worker_in = _worker_out = None
def _init_worker(input_path, output_path, shape, dtype):
global _worker_in, _worker_out
_worker_in = np.memmap(input_path, dtype=dtype, mode="r", shape=shape)
_worker_out = np.memmap(output_path, dtype=dtype, mode="r+", shape=shape)
def process_chunk(bounds):
start, end = bounds
_worker_out[start:end] = np.sqrt(_worker_in[start:end]) * 2.0
return bounds
def parallel_preprocess():
if not os.path.exists(INPUT_PATH):
mm = np.memmap(INPUT_PATH, dtype=DTYPE, mode="w+", shape=SHAPE)
mm[:] = np.random.default_rng(42).random(SHAPE[0]).astype(DTYPE)
mm.flush(); del mm
out = np.memmap(OUTPUT_PATH, dtype=DTYPE, mode="w+", shape=SHAPE)
out[:] = 0; out.flush(); del out
slices = [(i, min(i + CHUNK_SIZE, SHAPE[0])) for i in range(0, SHAPE[0], CHUNK_SIZE)]
with ProcessPoolExecutor(max_workers=os.cpu_count(), initializer=_init_worker,
initargs=(INPUT_PATH, OUTPUT_PATH, SHAPE, DTYPE)) as exe:
futures = [exe.submit(process_chunk, s) for s in slices]
for fut in as_completed(futures):
fut.result()
if __name__ == "__main__":
parallel_preprocess()
produced = np.memmap(OUTPUT_PATH, dtype=DTYPE, mode="r", shape=SHAPE)
source = np.memmap(INPUT_PATH, dtype=DTYPE, mode="r", shape=SHAPE)
expected = np.sqrt(source) * 2.0
matches = bool(np.allclose(produced, expected))
print(f"output.dat matches sqrt(input) * 2.0 for all {SHAPE[0]:,} elements: {matches}")
del produced, source, expected
os.remove(INPUT_PATH)
os.remove(OUTPUT_PATH)
Running this produces:
output.dat matches sqrt(input) * 2.0 for all 1,000,000 elements: True
a deterministic verification line instead of a raw wall-clock timing, since timing numbers vary by machine and would not reproduce for a reader running this elsewhere. The script computes sqrt(input) * 2.0 directly with numpy on the same seeded input, confirms every element the process pool actually wrote matches, then removes the memory-mapped files it created.
I/O-bound migration, without touching the existing blocking function:
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
def blocking_call(url): # existing synchronous code, unchanged
time.sleep(0.01) # stand-in for a blocking network call
return f"result for {url}"
urls = [f"https://example.invalid/{i}" for i in range(20)]
with ThreadPoolExecutor(max_workers=8) as pool:
futures = {pool.submit(blocking_call, u): u for u in urls}
for fut in as_completed(futures):
fut.result() # threads overlap the sleep/network-wait time
Trade-offs & pitfalls
- Multiprocessing's cost is process startup and inter-process communication (IPC): every argument and result crosses a pickle boundary, and naively passing large arrays duplicates memory per worker. Memory-mapped files or
multiprocessing.shared_memoryavoid the copy by letting workers map the same backing buffer instead of receiving a serialized copy. - Chunk size matters: too small, and scheduling/IPC overhead dominates; too large, and you lose load-balancing across workers. This has to be tuned per workload rather than assumed.
- Threads for the I/O case genuinely work, but they do not scale as far as
asynciofor very high fan-out (thousands of concurrent connections) because each thread carries OS-level stack and scheduling overhead that a coroutine does not. - A common wrong turn: reaching for
asyncio"because it's modern" on a CPU-bound bottleneck. It changes nothing about GIL contention and only adds complexity. - The thread-pool-around-blocking-code migration is a stopgap, not a long-term architecture: it still burns one OS thread per in-flight call, whereas a true
asynciorewrite trades that for a much larger number of lightweight coroutines. It is the right choice when a full rewrite is not affordable right now, not a permanent replacement for one.
Unlock Full Question Bank
Get access to all Python Programming interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.