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.
Explain how to structure a Python package to make it easy to test and maintain: where to place tests, use of init.py, how to expose a stable public API, and how to run tests in CI. Include best practices for type stubs and documentation.
Sample Answer
Project layout
- mypackage/
- src/mypackage/init.py # package implementation
- src/mypackage/module.py
- tests/ # unit tests
- test_module.py
- pyproject.toml / setup.cfg
Where to place tests
Keep tests outside package source (e.g., tests/ at repo root). This prevents accidental import of tests and mirrors CI test discovery.
init.py & public API
Use init.py to expose a stable public API with explicit imports and all. Keep implementation modules internal (e.g., mypackage._internal).
A concrete worked example of what that __init__.py and its module actually contain:
# src/mypackage/module.py
def process(data):
return [x * 2 for x in data]
def _internal_helper(): # leading underscore: not part of the public API
pass
# src/mypackage/__init__.py
from .module import process
__all__ = ["process"]
A caller then does from mypackage import process, process is the stable public name, while mypackage.module._internal_helper stays a private implementation detail nobody outside the package should import directly; __all__ also controls exactly what from mypackage import * pulls in.
Testing in CI
- Use pytest, run in CI (GitHub Actions) with matrix for Python versions. Run mypy (checks your type hints without actually running the code) and unit tests; fail on coverage thresholds.
A minimal CI job doing exactly that:
# .github/workflows/test.yml
jobs:
test:
strategy:
matrix:
python-version: ["3.11", "3.12"]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- run: pip install -e .[dev]
- run: pytest --cov=mypackage --cov-fail-under=80
- run: mypy src/mypackage
Type stubs & docs
- Add type hints in code; supply .pyi stubs (a
.pyifile is a type-hint-only file, holding no real code, for code Python itself cannot read type hints from directly, such as a compiled C extension) for compiled extensions. - Use Sphinx or MkDocs (both turn your docstrings into a browsable documentation website) for docs; generate API reference from docstrings. Include CI job to build docs.
Which of these matter most for a first working setup versus are polish added later: the src/ layout, an explicit __init__.py public API, and pytest running in CI are the essentials, without them the package is neither testable nor safely importable by other code. mypy, coverage thresholds, .pyi stubs, and generated documentation sites are all valuable, genuinely worth doing, but they are follow-up hardening once the basic package structure and test suite already exist, not blockers to a first working, publishable package.
Best practices: pin dev deps, run linters, and keep public surface minimal and documented.
Given a DataFrame df with millions of rows, you need to compute a new column 'rank_within_group' that ranks values within each group defined by 'category' in descending order. Write an efficient Pandas solution and explain memory and performance trade-offs.
Sample Answer
Goal: compute rank within each 'category' in descending order efficiently.
Solution:
import pandas as pd
# assuming df has columns ['category', 'value']
df = pd.DataFrame({
"category": ["A", "A", "A", "B", "B"],
"value": [10, 10, 8, 5, 5],
})
# use groupby + rank with method='dense' or 'first' depending on tie behavior
df['rank_within_group'] = df.groupby('category')['value']\
.rank(method='dense', ascending=False).astype(int)
method='dense' is the crux of the tie-breaking behavior here: it means tied values SHARE a rank, and the next distinct value continues at the very next rank number with no gap. That is different from method='first' (ties broken by row order, so no two rows ever share a rank) and from the default method='average' (ties get the average of the ranks they would have spanned). For descending values like 10, 10, 8, dense ranks them 1, 1, 2, not 1, 2, 3 (that would be method='first' or 'min'-adjacent behavior) and not 1.5, 1.5, 3 (that would be the average default).
Worked example, verified with pandas on CPython 3.12, including a genuine tie so the behavior is visible rather than only named:
df = pd.DataFrame({
"category": ["A", "A", "A", "B", "B"],
"value": [10, 10, 8, 5, 5],
})
df['rank_within_group'] = df.groupby('category')['value']\
.rank(method='dense', ascending=False).astype(int)
print(df)
Output:
category value rank_within_group
0 A 10 1
1 A 10 1
2 A 8 2
3 B 5 1
4 B 5 1
Category A's two tied 10s both get rank 1 (the highest, since ascending=False), and the next distinct value, 8, gets rank 2 immediately, no rank 3 is skipped to "make room" for the tie. Category B's two tied 5s both get rank 1, since within group B, 5 is the only (and therefore highest) value present.
Performance & memory:
- groupby.rank is implemented in C and avoids Python-level loops; it's fast and memory-efficient compared to apply.
- For millions of rows, ensure 'category' is categorical to save memory and speed grouping:
df['category'] = df['category'].astype('category')
- If memory is tight, process in chunks by categories: iterate over df.groupby('category') or sort by category and value and rank per chunk.
Trade-offs:
- In-memory groupby requires holding column arrays; converting to categorical reduces memory but adds preprocessing cost.
- Chunking reduces peak RAM but loses single-call simplicity and may require external sorting.
Explain dependency management approaches for Python: requirements.txt with pip, pip-tools, Pipenv, Poetry, and Conda. For a reproducible data-science project, which would you pick and why?
Sample Answer
Overview of approaches:
- requirements.txt + pip: Simple, exact package names; use pip freeze to pin. Reproducible only if you pin hashes (pip hash or requirements with hashes).
- pip-tools (pip-compile): Maintains human-editable top-level requirements.in and generates fully pinned requirements.txt (including sub-deps).
- Pipenv: Combines virtualenv + Pipfile/Pipfile.lock (a lock file records the exact version, and a hash, of every package actually installed, including indirect dependencies pulled in by your direct ones, so a second install reproduces the identical environment instead of silently picking up newer, still-technically-compatible versions); locking for reproducibility but has had stability/performance issues historically.
- Poetry: Modern tool for dependency resolution, pyproject.toml, and lock file; good for packaging and reproducible installs across environments.
- Conda: Manages packages and binaries (C libs) and environments; best when native dependencies (numpy, scipy) are needed.
Which of these is baseline knowledge versus niche: for most purposes, pip + a lockfile-pinned requirements.txt and Poetry are the two worth knowing well; pip-tools and Pipenv are reasonable alternatives worth recognizing as "another lockfile-based tool" rather than needing a strong independent opinion on; Conda (and micromamba, below) only becomes necessary once native, non-Python dependencies enter the picture.
My pick for reproducible data-science project: Poetry + Conda hybrid depending on needs.
- If heavy native deps: use Conda to create base env (python, BLAS, the compiled linear-algebra library numpy/scipy rely on internally for fast matrix math, and something Poetry itself cannot install since it only manages Python-level packages, not compiled system libraries), then Poetry for Python deps inside that env, or use micromamba (a faster, lighter-weight, drop-in alternative to the
condacommand line tool, installing from the same package channels) + poetry. Concretely:conda create -n proj python=3.12 numpy scipyto get the compiled base right, thenpoetry initandpoetry add pandasinside that environment to layer the pure-Python dependencies on top with a proper lockfile. Poetry gives clear lockfile, semantic project layout, and reproducible installs. pip-tools is a lighter alternative if you prefer pip. Ensure CI records exact lockfile and Python version.
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.
Describe how Python's reference counting and garbage collector work together to reclaim memory. Provide an example of an object pattern that requires the garbage collector (i.e., not reclaimed by reference counting alone).
Sample Answer
How they work together:
- CPython uses reference counting: each object tracks references; when count hits zero it's reclaimed immediately.
- The cyclic GC (generational, meaning it groups objects by how long they've survived so far and scans the youngest group most often, since most garbage dies young and rarely needs a second look) complements this by detecting reference cycles that reference counting alone can't free.
Example needing GC:
Two objects referencing each other (cycle) with del avoided or handled by GC. Example:
class Node:
def __init__(self):
self.ref = None
a = Node()
b = Node()
a.ref = b
b.ref = a
# If no external refs remain, ref counts are non-zero due to cycle -> GC must collect
Actually watching the reclamation happen, verified on CPython 3.12, extending the example above with a __del__ and an explicit gc.collect():
import gc
class Node:
def __init__(self, name):
self.name = name
self.ref = None
def __del__(self):
print(f'__del__ called for {self.name}')
a = Node('a')
b = Node('b')
a.ref = b
b.ref = a
del a, b # neither refcount reaches zero; both still reference each other
gc.collect() # the cyclic GC finds the unreachable pair and reclaims it
Output:
__del__ called for a
__del__ called for b
Both finalizers ran as part of gc.collect() reclaiming the cycle, confirming the cycle really was found and cleaned up, not just theoretically collectible.
Reference counting handles most deallocations quickly; the cyclic GC periodically finds unreachable cycles and reclaims them. Cycles involving objects with __del__ used to require special handling: on Python versions before 3.4, the cyclic GC could not safely decide what order to finalize such objects in, so it left them permanently uncollected in gc.garbage instead of guessing. Since Python 3.4 (PEP 442), __del__ is called safely as part of collecting the cycle, exactly as demonstrated above, and the objects are then reclaimed normally; citing the old "cycles with __del__ can't be collected" claim as current fact is a dated answer today.
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.