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.
Name a handful of Python standard library modules you reach for constantly in data-oriented work, parsing, compression, concurrency, data structures, and give a one-line reason for each.
Sample Answer
Direct answer
Five standard-library modules that come up constantly in data-oriented Python work: csv for reading and writing delimited files without loading everything into memory at once, gzip for transparent compression on data that moves through a pipeline, itertools for building memory-efficient iteration patterns (chunking, windowing), collections for purpose-built containers (Counter, defaultdict, deque) that replace hand-rolled counting and buffering logic, and datetime for parsing and normalizing timestamps consistently.
Structured elaboration
csv: streams rows from a delimited file one at a time via an iterator, so a multi-gigabyte export never has to sit fully in memory just to be transformed and reloaded elsewhere.gzip: reads and writes.gz-compressed data directly, useful for ingesting compressed log archives or writing compact intermediate files without shelling out to an external tool.itertools: composes lazy, memory-efficient iteration pipelines;isliceis the workhorse for turning any iterable into fixed-size chunks without building an intermediate list of everything first.collections:Counterreplaces a hand-rolleddictfrequency table,defaultdictremoves repeatedif key not in dchecks, and a boundeddequegives an O(1) fixed-size rolling buffer instead of manually trimming a list.datetime: normalizes timestamps to a consistent, timezone-aware representation, which matters the moment data arrives from more than one source with different (or missing) timezone conventions.
Worked example
Each, verified on CPython 3.12:
import csv, io
buf = io.StringIO("id,value\n1,10\n2,20\n")
rows = list(csv.DictReader(buf))
print(rows) # [{'id': '1', 'value': '10'}, {'id': '2', 'value': '20'}]
import gzip
payload = b"repeat this line\n" * 100
compressed = gzip.compress(payload)
assert gzip.decompress(compressed) == payload
print(len(payload), len(compressed)) # 1700 52
import itertools
def chunked(iterable, n):
it = iter(iterable)
while chunk := list(itertools.islice(it, n)):
yield chunk
print(list(chunked(range(10), 3))) # [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
from collections import Counter, defaultdict, deque
print(Counter("mississippi")) # Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})
d = defaultdict(list); d["a"].append(1)
print(dict(d)) # {'a': [1]}
dq = deque(maxlen=3)
for x in range(5): dq.append(x)
print(list(dq)) # [2, 3, 4]
from datetime import datetime, timezone
dt = datetime(2026, 7, 21, 12, 0, 0, tzinfo=timezone.utc)
print(dt.isoformat()) # 2026-07-21T12:00:00+00:00
Trade-offs & pitfalls
csv.DictReaderis convenient but re-creates a dict per row; for very large files where the per-row dict overhead itself matters,csv.reader(yielding plain lists) is cheaper, at the cost of accessing fields by position instead of name.gzip.compress/decompressoperate on the whole payload in memory; for files too large to hold fully in RAM, usegzip.openand read/write in a streaming loop instead of the one-shotcompress/decompressfunctions shown above.itertoolsfunctions are lazy by design, which is exactly the point for memory efficiency, but that also means a generator built from them is single-pass: iterating it a second time yields nothing, which surprises anyone expecting list-like reuse.defaultdict's automatic key creation is a footgun the moment you need to distinguish "key was never touched" from "key exists with the default value"; a plaindict.setdefaultor an explicitincheck is safer when that distinction matters.datetimeobjects without atzinfoare "naive" and silently compare or arithmetic-combine with other naive datetimes without any timezone reconciliation; mixing naive and timezone-aware datetimes in the same pipeline raisesTypeErrorat comparison time, which is usually the first sign a source is inconsistent about timezone handling.
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.
Explain positional, keyword, and default arguments in Python, plus *args and **kwargs. Write one function signature that uses all of them and describe when each pattern is idiomatic versus overkill.
Sample Answer
Direct answer
Python has four argument-passing shapes: positional (matched by order), keyword (matched by name), default values (make a parameter optional), and the catch-alls *args (extra positionals, collected as a tuple) and **kwargs (extra keywords, collected as a dict). They combine in one fixed signature order: positional-or-keyword params, then *args, then keyword-only params (which may have defaults), then **kwargs.
Structured elaboration
Signature order and what each piece means:
def process_batch(data, transform, *args, normalize=True, batch_size=100, **kwargs):
...
data,transform: positional-or-keyword, required. Callers usually pass these positionally because order is natural (the data, then what to do to it).*args: soaks up any extra positional arguments beyonddataandtransform, exposed inside the function as a tuple. Anything named after a bare*args(or a bare*) becomes keyword-only, meaning it cannot be passed positionally.normalize,batch_size: keyword-only parameters with defaults, so they are optional and callers must name them.**kwargs: soaks up any remaining keyword arguments not already named in the signature, exposed as a dict.
When each pattern is idiomatic versus overkill:
- Positional: idiomatic for the 1-2 arguments every call needs, in an order a reader can memorize. Overkill once a function takes more than 3-4 positional arguments; callers start passing things in the wrong order silently.
- Keyword + default: idiomatic for tunable, optional behavior (
batch_size,normalize) where the default covers the common case and the name documents intent at the call site. *args: idiomatic for genuinely variadic operations (print(*values), asum_all(*numbers)) or for forwarding positional arguments through a wrapper. Overkill as a substitute for a real, named parameter list; it hides the function's actual contract from anyone reading a call site.**kwargs: idiomatic for forwarding options to an underlying API you do not want to re-declare (backend-specific keys likeshuffleordevice), or for a plugin-style function whose exact options vary by caller. Overkill as a way to avoid deciding what a function's parameters actually are; unvalidated**kwargsswallows typos (nomralize=True) silently instead of raisingTypeError.
Worked example
def process_batch(data, transform, *args, normalize=True, batch_size=100, **kwargs):
results = []
for item in data:
value = transform(item, *args)
if normalize:
value = value / batch_size
results.append(value)
return results, kwargs
out, extra = process_batch(
[10, 20, 30],
lambda x: x * 2,
normalize=True,
batch_size=10,
shuffle=True,
device="cpu",
)
print(out) # [2.0, 4.0, 6.0]
print(extra) # {'shuffle': True, 'device': 'cpu'}
Here data and transform are passed positionally because every call needs them and the order is obvious; normalize and batch_size are named because they are optional tuning knobs; shuffle and device are not declared parameters at all, they arrive through **kwargs and the function forwards or ignores them as extra.
Trade-offs & pitfalls
- A bare
*with no name (def f(a, *, b):) is legal and forces everything after it to be keyword-only without collecting extra positionals; use it to make a signature self-documenting even when you do not need*args. **kwargsthat is never validated is a common production bug:transform_data(dat=my_df)(a typo ofdata=) silently lands inkwargsinstead of raisingTypeError: missing required argument. Pop and check known keys explicitly (kwargs.pop("shuffle", False)) if you accept**kwargs, or avoid it and declare the real parameter list.- Order matters and is enforced by the interpreter, not just style: positional-or-keyword parameters must come before
*args, which must come before keyword-only parameters, which must come before**kwargs; writing them out of order is aSyntaxErrorat definition time. - Mutable defaults are the sharpest edge here (
def f(items=[]):): a default value is evaluated once, when thedefstatement runs, not on each call, so a mutable default is shared and can accumulate state across unrelated calls.
You have a numeric inner loop in pure Python that can't be vectorized away and has to stay as a loop. What specific, code-level micro-optimizations would you apply, binding hot names to locals, avoiding repeated attribute lookups, minimizing function-call overhead inside the loop, and so on?
Sample Answer
Direct answer
Apply cheap, source-level changes first (binding hot names to locals, cutting per-iteration function-call overhead, using zip instead of index-based access), measure with a profiler to confirm they matter for this specific loop, and only then reach for a compiled path (Numba or Cython) if the loop is still the bottleneck after the cheap changes. None of this replaces vectorizing where vectorization is actually possible; this is specifically for the residual loop that cannot be vectorized away.
Structured elaboration
import math
# Before: repeated attribute lookups (math.sin, math.cos resolved on every call)
def compute_v1(data):
out = []
for x in data:
out.append(math.sin(x) + math.cos(x))
return out
# After: bind the hot names to locals once, outside the loop
def compute_v2(data):
sin = math.sin
cos = math.cos
out = []
for x in data:
out.append(sin(x) + cos(x))
return out
# Comprehension form: also avoids the repeated .append method lookup and call
def compute_v3(data):
sin = math.sin
cos = math.cos
return [sin(x) + cos(x) for x in data]
Worked example
Verified on CPython 3.12:
data = [0.1 * i for i in range(1000)]
r1, r2, r3 = compute_v1(data), compute_v2(data), compute_v3(data)
assert r1 == r2 == r3
All three produce identical results ([1.0, 1.094837581924854, 1.1787359086363027, ...]), confirming the rewrite is behavior-preserving, only its access pattern changed.
- Local binding:
math.sinis a global (module-attribute) lookup every time it is called inside the loop; assigningsin = math.sinonce turns every subsequent call into a local-variable lookup, which the interpreter resolves faster. - Avoiding repeated indexing: replacing
for i in range(len(a)): s += a[i] * b[i]withfor x, y in zip(a, b): s += x * ymoves the pairing work into a single C-implemented iterator instead of two separate__getitem__calls per step.
def dot_indexed(a, b):
s = 0.0
for i in range(len(a)):
s += a[i] * b[i]
return s
def dot_zip(a, b):
s = 0.0
for x, y in zip(a, b):
s += x * y
return s
a, b = [1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0]
assert dot_indexed(a, b) == dot_zip(a, b) == 70.0
- Minimizing function-call overhead: inlining a trivial helper (
y = x*x + 2*xinstead of calling a separatetransform(x)per element) removes one call/return per iteration; this is a real but usually small win, and trades away the readability and testability of a named helper, so it is worth reserving for loops that are already confirmed hot by a profiler. array/memoryviewfor numeric buffers, verified on CPython 3.12:
from array import array
N = 10
buf = array("d", [0.0]) * N
mv = memoryview(buf)
for i in range(N):
mv[i] = float(i * i)
print(list(buf)) # [0.0, 1.0, 4.0, 9.0, 16.0, 25.0, 36.0, 49.0, 64.0, 81.0]
A typed, contiguous array buffer avoids the per-element Python object overhead a plain list of floats carries, which matters when the loop's own body is cheap and object overhead dominates. A memoryview here is a lightweight wrapper that lets you read and write directly into buf's underlying memory via item assignment (mv[i] = ...), without copying the array's data or constructing a separate Python object layer the way indexing a plain list of floats would; that direct-memory-access property is the whole reason memoryview is used here instead of assigning into buf directly.
- Numba as the escalation path, verified on CPython 3.12 (
numbaJIT-compiles the annotated function to machine code the first time it runs):
import numpy as np
from numba import njit
@njit
def dot_numba(a, b):
s = 0.0
for i in range(a.shape[0]):
s += a[i] * b[i]
return s
a, b = np.array([1.0, 2.0, 3.0, 4.0]), np.array([5.0, 6.0, 7.0, 8.0])
assert dot_numba(a, b) == 70.0
Complexity: none of the local-binding, zip, or inlining changes alter the loop's asymptotic complexity; a loop that was O(n) stays O(n). The gain is a constant-factor reduction in per-iteration interpreter overhead, which is why profiling matters: a constant-factor win on a loop that is not actually the bottleneck does nothing for overall behavior. Compiling with Numba changes the constant dramatically (native machine code instead of the bytecode interpreter loop) without changing the algorithm's complexity class either; it does not turn an O(n2) algorithm into an O(n) one.
Trade-offs & pitfalls
- Edge case: binding a name to a local only helps if the loop actually calls it many times; for a loop that runs once or a handful of times, the extra local assignment is pure overhead with nothing to amortize it against.
- Edge case:
zipsilently stops at the shorter of its inputs ifaandbhave different lengths, which can mask a bug that an indexed loop (which would instead raiseIndexErroron the shorter one, or silently read past intent on the longer one) would surface differently; validate lengths up front if mismatched inputs are a real possibility, whichever loop style you use. - Edge case: Numba requires the function body to be expressible in a restricted, statically-typeable subset of Python (no arbitrary objects, limited dynamic dispatch) and pays a one-time compilation cost on first call for each distinct argument type signature; that compilation cost matters if the function is called only once or twice, and disappears into the noise if it is called many times in a hot path.
- Reach for Numba or Cython only once profiling (
cProfile,line_profiler, orpyinstrument) has actually identified this specific loop as the bottleneck; applying a compiled path preemptively adds build complexity, deployment considerations (a compiled extension, or Numba's LLVM dependency), and harder debugging for code that may not have needed it. - Micro-optimizing an inner loop is worthless if the surrounding code still allocates a fresh list, dict, or object per outer iteration; profile the whole pipeline, not just the loop body in isolation, before deciding where the actual time goes.
Explain what a metaclass is in Python and implement one that automatically registers every subclass of a base class into a global registry keyed by class name. Why would you reach for a metaclass here instead of, say, init_subclass?
Sample Answer
Direct answer
A metaclass is the class of a class: just as an ordinary class controls how its instances are created, a metaclass controls how classes themselves are created. type is the default metaclass for every class in Python; overriding type.__new__ (or __init__) lets you intercept class creation itself and inject behavior, such as recording every subclass in a registry, the moment a class statement finishes executing. __init_subclass__ is a lighter, more modern hook (added in Python 3.6, PEP 487) that runs after a subclass object already exists, which covers plain subclass registration perfectly well and is what most engineers should reach for first. The honest reason to reach for a full metaclass instead is that __init_subclass__ cannot act before the class object is built: it cannot rewrite the namespace or base classes, enforce a shared metaclass across unrelated hierarchies that must interoperate, or run validation that has to see the class dictionary before Python assembles it into a type.
Structured elaboration
Approach
- Define
RegistryMeta(type)and override__new__, which runs once per class statement, before the class object is returned. - Build the class as normal via
super().__new__(...), then, unless the class opts out (a sentinel attribute), record it in a module-level dict keyed by class name. - Attach the metaclass to a base class via
class Base(metaclass=RegistryMeta): ...; every subclass ofBaseautomatically goes throughRegistryMeta.__new__.
Worked example
# registry_meta.py
CLASS_REGISTRY = {}
class RegistryMeta(type):
def __new__(mcls, name, bases, namespace, **kwargs):
cls = super().__new__(mcls, name, bases, namespace)
if namespace.get("__abstract__", False):
return cls # skip the abstract base itself
CLASS_REGISTRY[name] = cls
return cls
class Plugin(metaclass=RegistryMeta):
__abstract__ = True
class CsvPlugin(Plugin):
pass
class JsonPlugin(Plugin):
pass
print(list(CLASS_REGISTRY.keys()))
Verified on CPython 3.12, this prints:
['CsvPlugin', 'JsonPlugin']
Plugin itself never appears, since it sets __abstract__ = True in its own namespace.
Key points
__new__on a metaclass runs before the class fully exists in the enclosing scope, so it is the correct place to reject or rewrite a class definition, not just observe it.- The
__abstract__sentinel pattern keeps the base class out of the registry without special-casing its name. - The registry itself is a plain module-level dict: O(1) lookup by class name, useful for plugin discovery and factory patterns (
CLASS_REGISTRY["CsvPlugin"]()).
Why reach for the metaclass here at all, given __init_subclass__ exists:
SIMPLE_REGISTRY = {}
class SimpleBase:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
SIMPLE_REGISTRY[cls.__name__] = cls
class Alpha(SimpleBase):
pass
class Beta(SimpleBase):
pass
print(list(SIMPLE_REGISTRY.keys())) # ['Alpha', 'Beta'], verified on CPython 3.12
For exactly the registration behavior asked about, this is fewer moving parts and does the identical job, no metaclass required. The genuine reason to prefer a metaclass is when you need to act before the class object exists, for example rejecting a malformed class outright instead of letting it get created and then complaining. __init_subclass__ only ever runs on an already-built class; it can veto by raising, but it cannot change what gets built. A metaclass's __new__ can inspect and reject the raw namespace before type.__new__ ever constructs the class:
class ValidatingMeta(type):
def __new__(mcls, name, bases, namespace, **kwargs):
if namespace.get("__abstract__", False):
return super().__new__(mcls, name, bases, namespace)
if "handle" not in namespace:
raise TypeError(f"{name} must define a 'handle' method (checked before class creation)")
return super().__new__(mcls, name, bases, namespace)
class Handler(metaclass=ValidatingMeta):
__abstract__ = True
class GoodHandler(Handler):
def handle(self):
return "ok"
try:
class BadHandler(Handler): # expected: no `handle` method, ValidatingMeta.__new__ rejects it
pass
except TypeError as e:
print(f'raises as expected: TypeError: {e}')
Verified on CPython 3.12: GoodHandler is created normally; the class BadHandler(Handler): pass statement itself raises immediately with TypeError: BadHandler must define a 'handle' method (checked before class creation), before BadHandler is ever bound as a name. __init_subclass__ can also raise on a missing method, but only after type.__new__ has already built the class object; the difference matters when the class body itself needs to be inspected or rewritten (adding methods, changing bases) rather than merely rejected.
Trade-offs & pitfalls
- The honest default: for plain subclass registration, prefer
__init_subclass__. It is simpler, needs nometaclass=boilerplate, and composes more predictably with multiple inheritance. Choosing a metaclass for a job__init_subclass__already does is over-engineering that a senior reviewer will flag. - Metaclasses justify themselves when you need pre-creation control (rewriting the namespace, enforcing constraints across classes that do not share a common base, or making the metaclass itself the unit of composition across independent hierarchies) or when integrating with a library that already defines its own metaclass and yours must cooperate with it (both must derive from a common metaclass, or Python raises
TypeError: metaclass conflict). - Name collisions in a
class name -> classregistry silently overwrite an earlier entry; keying by(module, name)or storing a list per name avoids losing an earlier plugin with the same class name defined in a different module. - A metaclass applies to every subclass in the hierarchy automatically, which is a feature for enforced registration but a footgun if a downstream user subclasses without realizing they inherited the metaclass's side effects (an unexpected registry entry, or an unexpected validation failure at class-definition time rather than at instantiation time).
- Complexity: registration is O(1) per class creation (a dict insert); the registry lookup is O(1). Edge cases: skip the sentinel base correctly (an off-by-one in the skip condition silently registers the abstract base itself); decide up front whether abstract intermediate classes in a deeper hierarchy should also be excluded, not just the root.
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.