Interview Q&A · Python · 25 questions in this topic

Scenario-Based Interview Questions — Python Interview Q&A

All Python topics

Engineering-judgment questions about production systems — debugging, profiling, caching, configuration, testing and migration decisions, with the trade-offs spelled out. Part of Scenario-Based Interview Questions · 375 questions in the Python bank.

How would you optimize slow Python code in a production application?

Answer

Profile first to find the actual bottleneck (never guess), then apply a targeted fix: better algorithm/data structure choice, caching repeated work, offloading to C-optimized libraries (NumPy), or parallelizing if the workload is genuinely CPU-bound.

A structured approach: (1) reproduce the slowness with a realistic workload, (2) profile with cProfile to find the actual hot path, (3) check if it's algorithmic (wrong Big-O complexity, data structure choice) before reaching for parallelism, (4) only then consider caching (lru_cache), vectorization, or concurrency.

Example

Example.pypython
# Step 1: Profile to find the actual bottleneck
import cProfile
cProfile.run("slow_function()")
# Step 2: Common fixes based on what profiling reveals
# - O(n^2) algorithm using nested loops -> switch to a set/dict for O(1) lookups
# - Repeated expensive computation -> @lru_cache
# - String concatenation in a loop -> "".join(parts) instead of += in a loop
# - Heavy numerical work -> NumPy vectorization instead of manual Python loops

💡 Lead with "I'd profile first" before naming any specific technique — interviewers specifically watch for candidates who jump straight to "I'd add caching/threads" without establishing where the actual time is going.

How would you process a 10 GB file that doesn't fit comfortably in memory?

Answer

Never load the whole file at once — process it line-by-line (for text) or in fixed-size chunks (for binary/non-lineoriented data) using generators, keeping memory usage constant regardless of file size and.

If the file needs multiple passes or complex aggregation, consider whether a streaming library (pandas with chunksize) or loading the data into a proper database for querying is more appropriate than hand-rolled streaming logic — the right tool depends on what you ultimately need to compute from the data.

Example

Example.pypython
def process_large_file(path):
    total = 0
    with open(path, encoding="utf-8") as f:
        for line in f: # one line in memory at a time
            if "ERROR" in line:
                total += 1
    return total
# For structured data too large for pandas' default in-memory approach:
import pandas as pd
for chunk in pd.read_csv("huge_file.csv", chunksize=100_000):
    process(chunk) # process 100k rows at a time instead of all 10 GB at once

💡 Ask a clarifying question if the format isn't specified — "is this a text log file, a CSV, or binary data?" — since the right chunking strategy differs; this shows structured thinking rather than assuming one universal answer.

How would you debug a memory leak in a long-running Python service?

Answer

Use tracemalloc (standard library) to snapshot memory usage at different points in time and compare them, identifying which objects are accumulating; also check for common leak sources — reference cycles involving __del__, growing caches with no eviction policy, and event listeners/callbacks that are registered but never unregistered.

"Memory leak" in Python usually doesn't mean truly unreachable memory (the garbage collector handles that) — it typically means objects are still reachable (and therefore never collected) because something is unexpectedly still holding a reference to them, often a module-level cache, a list that only ever grows, or a subscriber list.

Example

Example.pypython
import tracemalloc
tracemalloc.start()
snapshot1 = tracemalloc.take_snapshot()
# ... run the suspected leaking code for a while ...
snapshot2 = tracemalloc.take_snapshot()
top_stats = snapshot2.compare_to(snapshot1, "lineno")
for stat in top_stats[:5]:
    print(stat) # shows exactly which lines are allocating the most NEW memory

💡 Mention that a "memory leak" in a garbage-collected language almost always means "objects are unexpectedly still reachable," not "memory that's truly lost" — this framing shows you understand what's actually happening, not just how to run a diagnostic tool.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits