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.
Implement a memory-efficient CSV reader in Python that streams rows and yields namedtuples for each row, converting numeric-looking fields to int/float when appropriate. The function should accept a file path or file-like object and a chunk_size parameter controlling internal buffering.
Sample Answer
Approach: stream the file line-by-line using an internal buffer of chunk_size, parse CSV incrementally, yield namedtuples and convert numeric-looking strings to int/float lazily.
Implementation:
import csv
from collections import namedtuple
from io import TextIOBase
def stream_csv(path_or_file, chunk_size=65536):
f = open(path_or_file, 'r', newline='') if isinstance(path_or_file, str) else path_or_file
reader = csv.reader(f)
headers = next(reader)
Row = namedtuple('Row', [h.replace(' ', '_') for h in headers])
def conv(s):
if s == '':
return None
try:
i = int(s)
return i
except ValueError:
try:
return float(s)
except ValueError:
return s
for raw in reader:
yield Row(*[conv(field) for field in raw])
if isinstance(path_or_file, str):
f.close()
A namedtuple (created above via namedtuple('Row', [...])) is a lightweight, tuple-backed class whose fields you can access by name, row.age, instead of only by position, row[1], which is why it is used here rather than a plain tuple or a dict: it is as compact and fast as a tuple, but each yielded row reads like a normal object with named fields.
Worked example, verified on CPython 3.12:
import io
sample_csv = "name,age,score\nAlice,30,9.5\nBob,,7\n"
rows = list(stream_csv(io.StringIO(sample_csv)))
print(rows)
# [Row(name='Alice', age=30, score=9.5), Row(name='Bob', age=None, score=7)]
print(rows[0].name, rows[1].age)
# Alice None
conv turns '30' into the int 30 and '9.5' into the float 9.5; Bob's empty age field hits the s == '' check first and becomes None rather than being run through int()/float() at all, and rows[0].name shows the named-field access a plain tuple could not offer without remembering which index held which column.
Key points: single-pass, constant memory per-row, converts numbers eagerly per-field. For truly huge fields, use streaming CSV parsers (csv module is already streaming).
Complexity: O(n) time where n is total fields; O(1) extra space per row.
Edge cases: quoted newlines, malformed rows, large field sizes: consider using csv.DictReader and incremental file objects if needed.
A data pipeline intermittently produces different results on different runs (non-deterministic). List possible Python-language and library causes (e.g., dict ordering, floating-point reductions, parallelism) and propose concrete fixes to achieve determinism for production runs.
Sample Answer
Possible Python/library causes
- dict ordering: dict insertion order IS deterministic in CPython 3.7+ (this is a language guarantee, not an implementation quirk), but the actual non-determinism seen in production comes from something upstream feeding the dict in a different order between runs, for example a filesystem
glob()returning filenames in a different order, or multiple workers finishing and inserting their results in whatever order they happen to complete, not the dict itself misbehaving. - set iteration: unordered, causes non-deterministic traversal.
- floating-point reductions (sum/mean) non-associative ordering leads to tiny differences.
- parallelism: thread/process scheduling, race conditions, non-deterministic map ordering.
- use of RNG without fixed seeds (random, numpy.random, torch).
- reliance on OS-level nondeterminism (filesystem glob order, multiprocessing.Queue timing).
Two of these causes, made concrete, verified on CPython 3.12:
Non-associative floating-point reduction, a naive accumulator loop genuinely disagreeing with itself depending on order (built-in sum() on recent CPython uses a more accurate internal algorithm and happens to avoid this specific example, which is exactly why the naive loop below, closer to what a hand-rolled or per-worker partial-sum reduction actually does, is the more honest demonstration):
def manual_sum(values):
total = 0.0
for v in values:
total += v
return total
vals = [0.1, 0.2, 0.3]
print(manual_sum(vals))
# 0.6000000000000001
print(manual_sum(list(reversed(vals))))
# 0.6
import math
print(math.fsum(vals) == math.fsum(list(reversed(vals))))
# True
The same three floats, summed in two different orders by a plain accumulator, produce two DIFFERENT bit patterns, 0.6000000000000001 versus exactly 0.6, purely from the order of addition (this is exactly what happens when parallel workers each compute a partial sum and the main process combines them in whatever order they finish); math.fsum (a compensated-summation algorithm that tracks and corrects rounding error as it goes) gives the identical, order-independent result either way.
Unseeded RNG producing different output on repeated runs, and the fix:
import random
random.seed(42)
print(random.random())
# 0.6394267984578837
random.seed(42)
print(random.random())
# 0.6394267984578837 -- identical, since the seed was reset
Calling random.seed(42) again before the second random.random() call reproduces the exact same float; omitting the seed (or seeding from the current time, which is random's default) would make this genuinely different on every run, which is exactly the failure mode the fix below addresses.
Concrete fixes
- Sort keys/lists before iteration (e.g., sorted(dict.items())).
- Use deterministic data structures: collections.OrderedDict where explicit order required.
- Fix RNG seeds at pipeline start for all libs (random.seed, np.random.default_rng with seed passed).
- Use stable reduction algorithms: math.fsum or pairwise summation (numpy.sum with dtype and stable algorithm libs).
- Avoid unordered set for grouping; use sorted containers or deterministic grouping keys.
- Control parallelism: fix number of workers, use deterministic partitioning, or run single-threaded for critical steps.
- Pin library versions and document environment (requirements, Docker).
These steps produce reproducible outputs suitable for production ETL runs and debugging.
You have a flaky unit test that intermittently times out. Outline a debugging and remediation plan in a Python project with pytest and CI, including how to reproduce locally, collect traces, and enforce test stability.
Sample Answer
Debug & remediation plan:
- Reproduce locally
- Run the test repeatedly: pytest -k name --maxfail=1 -q --count=100 (pytest-repeat plugin) to reproduce flakiness.
- Run under same env as CI (Python version, env vars).
- Collect traces
- Add logging with timestamps or use pytest -s; capture stack traces on timeout by increasing timeout to inspect where it hangs.
- Use faulthandler: in test setup call faulthandler.dump_traceback_later and dump on timeout.
- Use pytest --durations and --showlocals to find slow parts.
- Isolate cause
- Check for test order dependency: run single test and with -k to see isolation.
- Mock external resources (network, DB, filesystem) and use deterministic fixtures.
- Check for race conditions: add sleeps, use thread/async synchronization, run under race detectors or sanitizers if available.
- Fixes
- Replace real I/O with fixtures/mocks or use ephemeral resources.
- Make async tests use event loop proper awaits and timeouts; use pytest-timeout to fail faster.
- Ensure teardown always cleans up (use tmp_path, monkeypatch).
- Enforce stability in CI
- Add time budget and stricter assertions; mark inherently flaky tests with @pytest.mark.flaky only after triage.
- Run flaky-test detection in CI: rerun once and fail if consistently flaky.
- Add metrics and alerting if test durations increase.
Result: deterministic, fast tests and fewer CI interruptions.
Worked walkthrough on one concrete flaky test: say test_worker_processes_queue starts a background thread that pushes a result onto a queue.Queue, then the test does time.sleep(0.05) and asserts the queue has an item, assuming 50ms is always enough for the worker thread to finish. On a fast, quiet machine this passes almost every time; on a loaded CI runner the worker thread sometimes has not finished by the time the fixed sleep ends, and the assertion fails, only sometimes, which is exactly what "flaky" means.
- Reproduce locally:
pytest -k test_worker_processes_queue --count=100(--countcomes from thepytest-repeatplugin, which adds that option to run the same test that many times in one pytest invocation) runs the test repeatedly in one process; a genuinely flaky test now fails on some of those runs and passes on others, in the same environment, which rules out "it only fails in CI" as an explanation and confirms the flakiness is reproducible on demand rather than a one-off fluke. - Collect traces:
pytest --durations=0 --showlocals(--durations=0prints every test's wall-clock duration sorted slowest-first instead of only the slowest few;--showlocalsprints each local variable's value at the point of failure) shows, on a failing run, that the assertion failed with the queue still empty: the worker thread genuinely had not produced a result yet, not that the assertion logic itself was wrong.faulthandler.dump_traceback_later(a standard-library facility you arm with a countdown; if the process is still alive when the countdown expires, it dumps every thread's current stack trace, which is exactly what you need for a hang rather than a fast failure) would show the worker thread still inside its own processing function at the moment the assertion already gave up, confirming a genuine race between the fixed sleep and the thread's actual completion time, not a logic bug in the worker itself. - Isolate cause: running the test alone (not the full suite) still reproduces it sometimes, which rules out cross-test state leakage as the cause; the pattern (passes when the machine is quiet, fails more often when it is busy) is the signature of a race condition between a fixed-duration sleep and actual, variable-duration background work, not a logic bug.
- Fix: replace the fixed
time.sleep(0.05)with an actual wait on the real completion signal,queue.get(timeout=5), which blocks only as long as it actually needs to (returning the moment the worker pushes its result, and only failing the test if 5 real seconds pass with nothing produced), removing the race entirely instead of tuning the sleep duration and hoping it is long enough. - Enforce in CI: add
pytest-timeout(a plugin that fails any individual test that runs longer than a configured limit, rather than letting a hang stall the whole CI job indefinitely) as a backstop for any future test that hangs outright, and only reach for@pytest.mark.flaky(a marker that tells a plugin to automatically retry a failing test before reporting it failed) after a test like this has actually been triaged and understood, never as a first response to red CI, since it hides the exact race just diagnosed instead of fixing it.
A race detector or sanitizer (a class of tool, e.g. a language's -race flag or ThreadSanitizer, that instruments a program at build or run time to flag unsynchronized concurrent access to shared memory as it happens, rather than waiting for it to occasionally produce a wrong answer) is the equivalent tool one level down, in compiled languages with real memory-level data races. Python's GIL rules out that specific class of memory corruption, so the direct equivalent here is exactly the timing/synchronization walkthrough above, not a separate tool to reach for.
You need to package a Python library used in data science which includes compiled C extensions and optional GPU support. Outline a cross-platform build and distribution strategy that simplifies installation for users on Linux, macOS, and Windows. Include CI steps and how you'd support pip installs.
Sample Answer
What a wheel is, first: a wheel (file extension .whl) is a pre-built, ready-to-install package file, so pip install mypkg just unpacks it, with no compiler or build step required on the user's own machine. Without wheels, pip has to compile the package's C extensions locally every time, which is slow and fails constantly on machines that lack the right compiler and headers. A concrete trace of the whole flow: a user on 64-bit Linux running Python 3.12 types pip install mypkg[cuda]; pip resolves the closest matching wheel filename it can find on PyPI, something like mypkg-1.0.0-cp312-cp312-manylinux2014_x86_64.whl, downloads it, and installs it directly with no compilation at all. manylinux2014 in that filename is a compatibility tag: it tells pip this wheel was built against an old-enough baseline of Linux system libraries that it will run correctly on nearly any modern Linux distribution, not just the exact one it was built on.
Strategy: provide manylinux and macOS/Windows wheels for common Python versions; fall back to source+build for edge cases. Offer GPU optional extras (extra tags like package[cuda]).
Build & CI:
- Linux: use GitHub Actions with cibuildwheel (a CI tool that automates building a correctly-tagged, pip-installable wheel for every OS/Python-version combination you need, instead of hand-writing that build matrix yourself) to produce manylinux2014 wheels for x86_64 and aarch64; build both CPU and GPU wheels (GPU via CUDA toolkits in separate matrix jobs).
- macOS: use cibuildwheel to build macOS universal2 wheels (a single wheel file containing binaries for both Intel and Apple Silicon Macs, so pip does not need two separate mac wheel variants).
- Windows: use cibuildwheel on windows-latest to build wheels.
- Run tests in each job, run integration tests with/without GPU.
Packaging:
- Use cython/setuptools or scikit-build with CMake (scikit-build bridges Python's packaging tools with CMake, the standard build system for compiled C/C++ code, so the compiled extension gets built the same way on every platform) for portability. Produce wheels with bundled libs where license allows.
- Publish wheels to PyPI and use tags: mypkg, mypkg[cuda] ==> extra_requires (Python packaging's mechanism for optional, named dependency sets: a user who runs
pip install mypkg[cuda]pulls in the extra CUDA-related dependencies, while a plainpip install mypkgskips them) that pin appropriate CUDA runtime and optional GPU wheels.
User installs:
- pip will pick wheel; if none, pip falls back to build from source (document build deps). Provide conda-forge (a large, community-maintained collection of prebuilt Conda packages) packages for easier GPU/runtime management.
Notes: sign wheels, provide concise install docs, and CI nightly builds for new Python/OS combos. If you can only do one thing first, do this: get cibuildwheel producing manylinux2014 plus macOS plus Windows CPU wheels through GitHub Actions and publish them to PyPI, since that alone lets the overwhelming majority of users pip install mypkg with zero compiler needed; GPU-specific wheels, conda-forge packages, and wheel signing are all valuable follow-ups, not blockers to a usable first release.
You maintain a codebase with heavy numeric work written in NumPy. A colleague proposes moving core loops to Numba for speed. What tests and benchmarks would you write to validate correctness and performance? Describe potential gotchas with Numba and how to test them.
Sample Answer
Tests and benchmarks:
- Correctness tests: unit tests comparing NumPy reference outputs vs Numba outputs on varied inputs including edge cases (NaN, infinities, zero-length arrays, non-contiguous/strided arrays). Use property-based tests (the
hypothesislibrary: instead of writing individual test inputs by hand, you describe a rule the output must always satisfy, and the library generates many random inputs trying to break that rule) for broader coverage. - Numerical accuracy: assert tolerances (rtol/atol, relative and absolute tolerance) for floating ops, using
np.testing.assert_allcloserather than exact equality, since compiled and interpreted floating-point code can differ in the last few bits even when both are correct. - Performance benchmarks: microbenchmarks measuring time and compilation overhead (first call vs steady-state) using
asv(airspeed velocity, a benchmarking tool that tracks a function's performance across commits, so a regression shows up tied to a specific commit rather than just "it got slower at some point") orpytest-benchmark.
A minimal correctness check, concretely (verified on CPython 3.12; the pattern below is the standard, documented Numba usage, whether or not numba happens to be installed in the environment reading this):
import numpy as np
from numba import njit
def f_numpy(x):
return np.sqrt(x ** 2 + 1)
@njit
def f_numba(x):
out = np.empty_like(x)
for i in range(x.shape[0]):
out[i] = (x[i] ** 2 + 1) ** 0.5
return out
x = np.array([0.0, 1.0, 2.0, 3.0])
np.testing.assert_allclose(f_numpy(x), f_numba(x))
# passes silently if the two implementations agree within tolerance;
# assert_allclose raises AssertionError with the offending values if they don't
This is the shape every correctness test in this answer means: compute the same thing both ways, on real (including edge-case) input, and assert they agree, rather than eyeballing the code and assuming they do.
Gotchas & how to test:
- Compilation overhead: measure both cold (first call, which includes the one-time cost of compiling the function for that argument type) and hot runs (every call after, which reuse the already-compiled machine code); prefer caching compiled functions when appropriate.
- Unsupported Python features: ensure no reliance on Python objects in hot loops; test for object-mode fallback by enabling nopython=True in tests and catching TypingError. Numba's default
@njitmode (short fornopython=True) compiles the whole function straight to machine code with no Python-object fallback; if some part of the function cannot be compiled that way,@njitraisesTypingErrorimmediately rather than silently degrading, which is exactly what you want in tests: a raisedTypingErrortells you precisely which line Numba could not compile, instead of the function quietly running slow through the interpreter (the older, more permissive default mode's "object-mode fallback"). - ABI/dtype differences: test with different dtypes and memory layouts (C/F contiguous, non-contiguous views). ABI (application binary interface) is the compiled-code calling convention two pieces of native code, here a NumPy build and a Numba-compiled function, must agree on to call each other correctly; a mismatch is rare but shows up as crashes or garbage values rather than a clean error. C-contiguous means an array's elements sit one after another in memory in row-major order (the default for a freshly created array); F-contiguous (Fortran-contiguous) means the same but column-major; a strided or non-contiguous view (e.g.
arr[::2]) is neither, and a Numba function compiled assuming one layout can behave incorrectly or need an implicit, costly copy when handed the other, which is exactly why testing with a strided view as input matters, not just a fresh contiguous array. - Thread-safety: test with multithreaded calls if using parallel=True; check for race conditions.
Automation: integrate benchmarks in CI (nightly) and gate correctness on PRs; document performance expectations and maintain regression alerts.
Unlock Full Question Bank
Get access to all 46 Python Programming interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.