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.
Why can a tuple be used as a dictionary key or set member while a list can't? Walk me through what makes an object hashable in Python, and what invariant must hold between hash and eq for a type to be safely usable as a key.
Sample Answer
Direct answer
A tuple can be a dict key or set member because it is immutable and, as long as everything inside it is itself immutable, hashable; a list cannot, because lists are mutable and Python refuses to hash mutable containers. The invariant that makes any object safely usable as a hash-table key is: if two objects compare equal (a == b), they must produce the same hash (hash(a) == hash(b)); the reverse is not required (unequal objects may share a hash, that is just a collision to be resolved). Hashability in CPython means "defines __hash__", and that hash value must never change for the lifetime of the object while it is a key or set member, which is why mutable types either omit __hash__ or, for user classes, have it silently disabled the moment you define __eq__ without also defining __hash__.
Structured elaboration
Why mutability breaks hashing. A dict finds a key by computing hash(key) once at insertion time and using it to pick a slot. If the key's value (and therefore its hash) could change after insertion, the entry would sit in the wrong slot for its new hash, and a later lookup with the same object would compute a different hash and look in the wrong place, silently failing to find it, or corrupting the table depending on how the collision chain unwound. Python avoids this whole class of bug by making list, dict, and set unhashable, and making tuple hashable only when its contents are hashable (a tuple is a fixed-size, ordered container, but it is only as hashable as what's inside it).
The __hash__/__eq__ contract. For a type to be safely usable as a dict key or set member:
a == bimplieshash(a) == hash(b). This is the invariant that actually matters: if you break it, two "equal" objects can land in different hash-table slots, and a lookup by one will fail to find the entry stored under the other, even though the container logically already has that key.hash(a)must be stable for the object's lifetime as a key (an object should not become externally observably different, from the hash table's perspective, after insertion).- Python's default behavior for user classes reflects this: if you define
__eq__without defining__hash__, Python sets__hash__toNonefor that class (making instances unhashable), because the compiler cannot verify your custom__eq__still satisfies rule 1 against the default identity-based hash.
Where this shows up with tuples.
(1, 2)is hashable: both elements are immutable ints.(1, [2, 3])is NOT hashable: it contains a list, sohash()raisesTypeError, even though the outer tuple itself cannot be mutated.frozensetis the immutable, hashable counterpart toset, useful as a key when you need "a set of things" as the key itself.collections.namedtuple(andtyping.NamedTuple) are still plain tuples under the hood, so they remain hashable under the same rule and add named-field readability with no extra runtime cost over a positional tuple.
Worked example
t = (1, 2)
print(hash(t))
# some integer, e.g. -3550055125485641917
try:
hash([1, 2])
except TypeError as e:
print("TypeError:", e)
# TypeError: unhashable type: 'list'
try:
hash((1, [2, 3])) # tuple containing a list is still unhashable
except TypeError as e:
print("TypeError:", e)
# TypeError: unhashable type: 'list'
Defining __eq__ without __hash__ makes a class unhashable, demonstrating the contract directly:
class Point:
def __init__(self, x):
self.x = x
def __eq__(self, other):
return self.x == other.x
# no __hash__ defined -> Python sets __hash__ = None here
try:
hash(Point(1))
except TypeError as e:
print("TypeError:", e)
# TypeError: unhashable type: 'Point'
Using a tuple as a composite grouping key (a common real use):
from collections import defaultdict
rows = [
{"user_id": 1, "date": "2025-11-01", "value": 10},
{"user_id": 1, "date": "2025-11-01", "value": 5},
{"user_id": 2, "date": "2025-11-02", "value": 7},
]
totals = defaultdict(int)
for r in rows:
key = (r["user_id"], r["date"]) # tuple: immutable and hashable
totals[key] += r["value"]
# totals == {(1, '2025-11-01'): 15, (2, '2025-11-02'): 7}
Trade-offs & pitfalls
- A tuple is only hashable if all of its elements are; a tuple of lists, dicts, or sets is not, and you will find this out at runtime with a
TypeError, not at write time. - If you define
__eq__on a class and want instances to remain usable as dict keys or set members, you must also define a compatible__hash__(or explicitly reuse the default with__hash__ = object.__hash__if identity equality is acceptable); forgetting this is a common way custom value objects silently become unhashable. - Violating the "equal implies equal hash" invariant (defining
__eq__and a__hash__that disagrees with it) does not raise an error; it produces "impossible" bugs wherekey in some_dictreturnsFalsefor a key that logically should match, because the two objects hashed into different slots. namedtupleandfrozensetare the two common upgrades once a plain tuple's positional-only access, or a plain tuple's ordering, respectively, stops being convenient, both without giving up hashability.
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.
Walk me through try/except/else/finally in Python: what runs when, and how would you structure exception handling around a file read that must clean up regardless of outcome? When should code catch a broad Exception versus a specific exception class?
Sample Answer
Direct answer
try holds the risky code; except runs only if a matching exception was raised, and is skipped entirely if nothing went wrong; else runs only if the try block completed with no exception, which is the right place for code that should run on success but that you do not want except to accidentally catch errors from; finally always runs, exception or not, and is for cleanup you need guaranteed regardless of outcome. For a file read that must clean up, put the open and the read in try, the failure handling in except, the "it worked" logic in else, and the close in finally.
Structured elaboration
Execution rules, precisely:
tryblock runs.- If it raises, Python looks for a matching
exceptclause (top to bottom); the first one whose exception type matches runs, and the rest are skipped. - If it raises no exception, the
elseblock runs (this is the part people forget exists). finallyruns last, no matter which of the above happened, including if thetry,except, orelseblock returned a value or raised a new/uncaught exception.
Why else earns its own block instead of just putting that code at the end of try: if you put "the code that should only run on success" inside try itself, and it happens to raise the same exception type your except is watching for, you would silently swallow a bug in your success-path code and misreport it as the original failure. else runs outside the try's exception net, so only the risky operation is actually guarded.
Broad Exception versus a specific exception class:
- Catch a specific exception class (
FileNotFoundError,KeyError,ValueError) when you know exactly what can go wrong and have a distinct, correct recovery for it. - Catching bare
Exception(or worse, bareexcept:, which also catchesKeyboardInterruptandSystemExitviaBaseException) is appropriate only at a genuine top-level boundary, such as a request handler or a batch-job wrapper, where the goal is "log this and don't crash the whole process" rather than "recover meaningfully." Even then, log the exception with its traceback and re-raise or fail the specific job, don't swallow it silently.
Worked example
def read_config(path):
try:
f = open(path, "r")
except OSError as e:
print(f"could not open {path}: {e}")
return None
try:
data = f.read()
except UnicodeDecodeError as e:
print(f"could not decode {path}: {e}")
return None
else:
print(f"read {len(data)} characters successfully")
return data
finally:
f.close()
print("file handle closed")
with open("sample.txt", "w") as f:
f.write("hello world")
result = read_config("sample.txt")
print("result:", result)
# read 11 characters successfully
# file handle closed
# result: hello world
result2 = read_config("does_not_exist.txt")
print("result2:", result2)
# could not open does_not_exist.txt: [Errno 2] No such file or directory: 'does_not_exist.txt'
# result2: None
Note the open itself is guarded separately: if open() fails there is no file handle for finally to close, so that failure returns early before the second try/except/else/finally block, which owns the read and the guaranteed close.
Trade-offs & pitfalls
- The idiomatic modern version of "must clean up regardless of outcome" for a file is
with open(path) as f:, a context manager, which calls the equivalent offinally: f.close()for you and is shorter and harder to get wrong. Hand-rolledtry/finallycleanup is worth knowing (it is howwithis implemented under the hood, and applies to resources that aren't files) but should not be your first choice when a context manager already exists. finallyrunning "no matter what" includes overriding areturnintry: areturninsidefinallysilently discards whatevertryorexceptwas about to return, which is a real, hard-to-spot bug. Avoid returning fromfinally.- Catching an exception you cannot meaningfully handle (just to
pass) hides real bugs; if you cannot recover, let it propagate, or catch, log, and re-raise.
Given a shared counter incremented by several threads in a tight loop with count += 1, why does the final count come out wrong even though the GIL exists? Provide a corrected, efficient version, and explain which Python operations are actually safe to share across threads without a lock and which aren't.
Sample Answer
Direct answer
The Global Interpreter Lock (GIL) guarantees that only one thread executes Python bytecode at a time, but it does not make count += 1 a single, uninterruptible step. That statement compiles to several bytecode operations (load the current value, add one, store the new value), and the GIL can hand control to another thread in between any two of them. Two threads can both read the same old value before either writes back the incremented one, so an increment gets lost. The fix is to protect the whole read-modify-write with a lock (or have each thread accumulate locally and merge once), not to assume the GIL alone provides atomicity.
Structured elaboration
Why the GIL doesn't save you: the GIL prevents two threads from running Python bytecode simultaneously, but threads still interleave, control passes back and forth between them constantly. count += 1 is not one bytecode instruction; it is a small sequence, and the interpreter can switch threads between any of those instructions. If thread A reads count as 5, then control passes to thread B, which also reads 5, increments to 6, and writes back, then control returns to thread A, which still has 5 in hand, increments to 6, and writes 6 again, one increment from B is silently lost.
What's actually safe to share without a lock, and what isn't:
- Safe: a single, atomic operation on an immutable value, for example rebinding a name to point at a brand-new object (
x = new_value) is effectively atomic at the bytecode level because CPython's reference-count updates (CPython keeps a running count, on every object, of how many names or containers currently point to it, and updates that count whenever a name is bound or rebound; that single count update is what happens atomically here) for the old and new objects happen under the GIL without another thread's bytecode interleaving inside that singleSTOREstep. - Not safe: any compound operation, no matter how short it looks in source:
count += 1,d[k] = d.get(k, 0) + 1,list.appendfollowed later by readinglen(list)to decide something,if not cache: cache = build()(check-then-act). All of these are read-then-write (or read-then-branch-then-write) and can interleave. - The rule of thumb: if the line reads a shared value and then writes back something derived from what it read, it needs a lock, regardless of how atomic-looking the syntax is.
This is the same defect wearing three different costumes, and the fix is identical each time (protect the read-modify-write, or the check-then-act, with a lock):
- Shared counter (this question):
count += 1from multiple threads. - Shared dict:
d[k] = d.get(k, 0) + 1is exactly as compound as the counter case; two threads can race on the same key and lose an update the same way. - Lazy singleton:
if instance is None: instance = build()is a check-then-act; two threads can both seeNone, both callbuild(), and end up with two different instances (or worse, two objects doing conflicting side effects during construction) unless the check and the assignment are both inside the same lock.
Worked example
The race, made reliably observable (verified on CPython 3.12). A natural count += 1 loop rarely shows lost updates in a short demo, because the read and the write-back usually land close enough together that no thread switch happens to fall between them, forcing a time.sleep(0) between the read and the write makes the interleaving deterministic instead of leaving it to chance:
import threading, time
count = 0
def worker(n):
global count
for _ in range(n):
temp = count # read
time.sleep(0) # forces a thread switch between read and write-back
count = temp + 1 # write
threads = [threading.Thread(target=worker, args=(200,)) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
print(count, "expected", 800)
Three separate runs of this produced 225, 270, and 238 against an expected 800: the exact number is not reproducible run to run (it depends on the OS thread scheduler), but it is reliably and substantially below 800 every time, which is the point being demonstrated: lost updates, not a specific count.
Corrected, efficient version: each thread accumulates a local total (no shared state, no lock needed for that part) and merges into the shared counter once at the end, so lock contention happens once per thread instead of once per increment:
import threading
count = 0
count_lock = threading.Lock()
def worker(n):
global count
local = 0
for _ in range(n):
local += 1 # purely local, no synchronization needed
with count_lock:
count += local # one synchronized update per thread
threads = [threading.Thread(target=worker, args=(200_000,)) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
print(count) # 800000, exactly, on every run
This produced exactly 800000 across repeated runs, matching 4 * 200_000 precisely, because there is now only one lock-protected read-modify-write per thread instead of one per increment.
The same lesson applied to a shared dict and a lazy singleton, both verified on CPython 3.12:
import threading
# Shared dict: same compound read-modify-write as the counter.
counts_lock = threading.Lock()
counts = {}
def bump(key, n):
for _ in range(n):
with counts_lock:
counts[key] = counts.get(key, 0) + 1
threads = [threading.Thread(target=bump, args=("hits", 50_000)) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
print(counts["hits"]) # 200000, exactly
# Lazy singleton: same check-then-act race, fixed with double-checked locking.
class Config:
_instance = None
_lock = threading.Lock()
@classmethod
def get_instance(cls):
if cls._instance is None: # fast path, no lock in the common case
with cls._lock:
if cls._instance is None: # re-check: another thread may have
cls._instance = cls() # already built it while we waited
return cls._instance
Trade-offs & pitfalls
- Complexity: the corrected counter does O(n) work per thread with O(1) lock acquisitions per thread (not per increment), versus O(n) lock acquisitions in a naive "lock every increment" fix; batching the merge is what keeps contention low.
- A naive fix that locks every single increment is correct but pays full lock overhead n times per thread; that overhead, not correctness, is the usual reason it gets flagged as inefficient.
- The single-check
if instance is None: instance = build()singleton pattern looks obviously wrong once you frame it as check-then-act, but it is one of the most common places this bug actually ships, because it is rarely exercised under real contention until traffic spikes. - Common wrong turn: reaching for
collections.Counteror a plaindictand assuming built-in types are internally synchronized against interleaved compound updates from multiple threads; they are not, their individual C-level operations may be atomic, butget-then-setacross two separate operations is not. - Edge case: the demo above uses an inserted
time.sleep(0)to force the race to show up reliably; without it, whether a given run of an unprotectedcount += 1loop actually shows a wrong answer depends on thread count, iteration count, and the OS scheduler, so an unprotected version passing a quick manual test is not evidence it is safe.
What's the difference between repr and str on a Python class? Write a small class that implements both, showing the developer-facing versus user-facing representation.
Sample Answer
Direct answer
__repr__ returns the developer-facing representation: unambiguous, ideally something that could recreate the object, and shown in the REPL and inside containers. __str__ returns the user-facing representation: readable, meant for print() and str() calls. If a class defines only __repr__, Python falls back to it for str() too, so __repr__ is the one you should always implement; __str__ is the optional, friendlier layer on top.
Structured elaboration
Where each one gets called:
print(obj)andstr(obj)call__str__; if it is not defined, Python falls back to__repr__.repr(obj), the interactive REPL echoing a value, and displaying an object inside a container (a list, dict, or tuple) all call__repr__, always, even if__str__is defined. This is a common surprise:print([my_object])shows thereprofmy_object, not itsstr.- Both should be deterministic and side-effect free; neither should do expensive work like a network call or a database lookup.
Design guidance:
__repr__: aim for something likeClassName(field=value, ...)so a reader (or theeval()of the string, when feasible) can reconstruct the object's state.__str__: aim for a short, human sentence, useful in logs, dashboards, or error messages shown to non-developers.- If the two would be identical, just implement
__repr__and skip__str__entirely; do not duplicate the same string in both methods.
Worked example
class Record:
def __init__(self, record_id, features):
self.record_id = record_id
self.features = tuple(features)
def __repr__(self):
return f"Record(record_id={self.record_id!r}, features={self.features!r})"
def __str__(self):
return f"Record {self.record_id}: {len(self.features)} features"
r = Record(42, [0.1, 0.2, 0.3])
print(repr(r)) # Record(record_id=42, features=(0.1, 0.2, 0.3))
print(str(r)) # Record 42: 3 features
print(r) # Record 42: 3 features (print uses __str__)
print([r]) # [Record(record_id=42, features=(0.1, 0.2, 0.3))] (container display uses __repr__)
The last line is the detail people miss: even though Record defines a friendly __str__, wrapping it in a list and printing shows the __repr__ form, because container repr always renders its elements with their repr.
Trade-offs & pitfalls
- Skipping
__repr__and only writing__str__is the wrong way around: without__repr__, debugging in a REPL or reading a log traceback shows Python's default<Record object at 0x7f...>, which tells you nothing about the object's state. - Do not put secrets or large blobs in
__repr__; because it is used in error messages, tracebacks, and log lines, an unfiltered__repr__on an object holding an API key or a full feature vector for a million-row dataset can leak sensitive data into logs or make debugging output unreadable. Truncate or redact. - For a
dataclass,@dataclassgenerates a reasonable__repr__automatically (field=value for every field) but no__str__; you still write__str__yourself if you want a friendlier display form. - Keep
__repr__deterministic (no unordered dict/set field showing in a different order per call) so log diffs and test assertions are stable.
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.