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.
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.
Given a NumPy array a of shape (N, M), write Python code to compute a boolean mask of rows that contain any NaN using vectorized NumPy operations. Do not use Python loops.
Sample Answer
Vectorized mask for rows containing any NaN:
import numpy as np
# a is shape (N, M)
mask = np.isnan(a).any(axis=1)
Explanation:
- np.isnan(a) produces boolean array shape (N, M).
- .any(axis=1) reduces per row to True if any element is NaN. A numpy axis names which direction a reduction collapses across for a 2D array: axis=0 collapses DOWN each column (one result per column), axis=1 collapses ACROSS each row (one result per row); since the question asks for a per-row answer, one True/False per row of the (N, M) array, axis=1 is the one that produces exactly N results, matching the number of rows.
Worked example, verified on CPython 3.12:
a = np.array([[1.0, 2.0], [np.nan, 4.0], [5.0, 6.0]])
print(np.isnan(a))
# [[False False]
# [ True False]
# [False False]]
print(np.isnan(a).any(axis=1))
# [False True False]
Row 0 ([1.0, 2.0]) has no NaN, so it reduces to False; row 1 ([nan, 4.0]) has one, so it reduces to True; row 2 ([5.0, 6.0]) has none, so False again, exactly the boolean mask a caller would use to filter out or flag the bad row.
This is fully vectorized, memory-efficient (single boolean array) and avoids Python loops. For very large arrays consider processing in chunks to limit peak memory.
Write a Pandas expression (or minimal code) to pivot a DataFrame df with columns ['user', 'metric', 'value'] into a wide DataFrame with one row per user and each metric as a column. Handle duplicate user-metric pairs by taking the last value. Show how to do this efficiently for large data.
Sample Answer
Solution (Pandas): use pivot_table taking last value for duplicates and use efficient grouping to limit memory.
import pandas as pd
df = pd.DataFrame({
"user": ["u1", "u1", "u1", "u2", "u2"],
"metric": ["score", "score", "clicks", "score", "clicks"],
"value": [10, 15, 3, 20, 7],
})
# pivot using last observation
wide = df.pivot_table(index='user', columns='metric', values='value', aggfunc='last')
# optional: reset index
wide = wide.reset_index()
Worked example, verified with pandas on CPython 3.12, including a genuine duplicate (user, metric) pair so the tie-breaking behavior is visible:
df = pd.DataFrame({
"user": ["u1", "u1", "u1", "u2", "u2"],
"metric": ["score", "score", "clicks", "score", "clicks"],
"value": [10, 15, 3, 20, 7],
})
print(df)
wide = df.pivot_table(index='user', columns='metric', values='value', aggfunc='last').reset_index()
print(wide)
Input:
user metric value
0 u1 score 10
1 u1 score 15
2 u1 clicks 3
3 u2 score 20
4 u2 clicks 7
Output:
metric user clicks score
0 u1 3 15
1 u2 7 20
u1 has two score rows (10 then 15); aggfunc='last' keeps whichever one appears LAST in df's row order, 15, and silently drops 10. This is the actual behavior the question asks about: the row order of the input DataFrame determines which duplicate value survives, so if "last" is meant to be "most recent by time" rather than "however the rows happened to arrive," the DataFrame must be sorted by a timestamp column first, pivot_table itself has no notion of time, only of row order.
Efficient for large data:
- If df is very large, pre-sort so last() works correctly: df.sort_values(['user','metric','timestamp'], inplace=True) then drop_duplicates keeping='last' then pivot.
# memory-friendly: deduplicate then pivot
df = pd.DataFrame({
"user": ["u1", "u1", "u1", "u2", "u2"],
"metric": ["score", "score", "clicks", "score", "clicks"],
"value": [10, 15, 3, 20, 7],
"timestamp": pd.to_datetime([
"2024-01-01", "2024-01-03", "2024-01-02", "2024-01-01", "2024-01-03"
]),
})
df2 = df.sort_values(['user','metric','timestamp']).drop_duplicates(['user','metric'], keep='last')
wide = df2.pivot(index='user', columns='metric', values='value').reset_index()
This second code block is an ALTERNATIVE to the pivot_table(aggfunc='last') call above for large data, not a required second step after it: pivot_table with aggfunc='last' already handles duplicates correctly on its own, this version exists purely because pre-deduplicating (drop_duplicates) before a plain pivot (which requires already-unique index/column pairs and raises otherwise) can be cheaper at scale than letting pivot_table do the deduplication and aggregation together internally.
Notes: drop_duplicates reduces rows before pivoting to lower memory. Use categorical for 'metric' to reduce memory. For extreme scale, use Dask DataFrame (a library that mirrors the Pandas API but splits data into partitions and runs the same operations, including pivot-style reshaping, across them in parallel) with same operations, once the table genuinely no longer fits on one machine; plain Pandas, as shown above, is enough below that point.
Write a function merge_sorted_iterables(iters, key=None) that merges multiple sorted iterables (which may be generators) into a single generator yielding elements in sorted order. Use only standard library modules. Explain memory characteristics.
Sample Answer
Approach: Use a min-heap (a min-heap is a tree-shaped data structure that always keeps its smallest element accessible at the top/root, retrievable in O(1), and restores that property in O(log n) after every push or pop; that is what lets this algorithm always grab the smallest available head-of-iterable next without rescanning every input from scratch) to pull the smallest next element from heads of each iterable. Support key by pushing (key(val), idx, val, iterator). Works with generators and streams and only holds one item per input plus heap overhead.
Implementation:
import heapq
import itertools
def merge_sorted_iterables(iters, key=None):
key = (lambda x: x) if key is None else key
heap = []
for idx, it in enumerate(map(iter, iters)):
try:
val = next(it)
heapq.heappush(heap, (key(val), idx, val, it))
except StopIteration:
continue
while heap:
_, idx, val, it = heapq.heappop(heap)
yield val
try:
nxt = next(it)
heapq.heappush(heap, (key(nxt), idx, nxt, it))
except StopIteration:
continue
Worked example, verified on CPython 3.12:
print(list(merge_sorted_iterables([[1, 4, 7], [2, 3, 9]])))
# [1, 2, 3, 4, 7, 9]
Tracing the heap: it starts holding one entry per input, (1, 0, 1, iter1) and (2, 1, 2, iter2), the smallest head of each list. Popping the smaller one yields 1 and immediately pushes that same iterator's next value, 4, back in, so the heap always holds exactly one "candidate next value" per iterable that still has values left. Popping the current minimum of that small set is always correct because every value not yet pulled from a given iterable is guaranteed to be >= the value currently sitting in the heap for it, since each input is already sorted; the full sequence of pops is 1, 2, 3, 4, 7, 9, matching the printed output exactly.
Key points:
- Memory: O(m) where m = number of input iterables (one element per iterator + heap metadata).
- Works with infinite streams and generators.
- Stable per iterator due to idx tie-breaker.
Edge cases: empty iterables, differing element types (ensure key handles them), expensive key (consider caching keys).
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.