Python interview questions: 30 questions with answer outlines
Core language, practical, behavioral and situational questions for Python developer roles, each with what the interviewer looks for and how to structure a strong answer.
Last updated 22 October 2026
What do Python developer interviews test?
Python interviews test whether you understand how the language behaves, not just its syntax: mutability and copying, generators, decorators, context managers, the GIL and asyncio, typing and dataclasses. Expect testing with pytest, a debugging or performance problem, and behavioral questions about code review, deadlines and production bugs.
What are the top 30 Python interview questions?
Every question below is listed here with its type and level, then answered in full in the sections that follow. Select a question to jump to its answer outline.
Which core Python questions come up most?
These check your model of the language itself. Answers assume CPython 3.12 or later; where behavior changed between versions, the outline says so.
1. What is the difference between a list and a tuple, and when would you choose each?
Level: Entry. What the interviewer looks for: Mutability and its consequences (hashability, use as dict keys), not just “tuples are faster”.
How to answer:
- A list is mutable; a tuple is immutable once created.
- A tuple is hashable if all its elements are hashable, so it can be a dict key or set member; a list never can.
- Use tuples for fixed records (coordinates, rows, multiple return values) and lists for collections that grow or change.
- Immutability of the tuple is shallow: a tuple holding a list can still have that list changed.
2. What goes wrong with def add(item, items=[]), and how do you fix it?
Level: Entry. What the interviewer looks for: Knowing default values are evaluated once, when the function is defined, and the standard None-sentinel fix.
How to answer:
- The default list is created once at definition time and shared by every call that omits the argument, so items pile up across calls.
- Fix: default to None and create a new list inside the function (
if items is None: items = []). - The same applies to dicts, sets and other mutable defaults; in dataclasses use
field(default_factory=list).
3. What is the difference between is and ==?
Level: Entry. What the interviewer looks for: Identity versus equality, and knowing is is only appropriate for singletons such as None.
How to answer:
==compares values by calling__eq__;ischecks whether two names refer to the same object.- Use
isfor singletons:x is None,x is not None. - Do not rely on
isfor numbers or strings; small-int caching and string interning are implementation details.
4. Are Python dictionaries ordered? Since when, and what does that guarantee?
Level: Entry. What the interviewer looks for: Insertion order is a language guarantee from Python 3.7; awareness of what “ordered” does and does not mean.
How to answer:
- Yes: dicts preserve insertion order, guaranteed by the language since Python 3.7 (it was a CPython detail in 3.6).
- Updating an existing key keeps its position; deleting and re-inserting moves it to the end.
- Two dicts with the same items in a different order still compare equal;
OrderedDictadds order-sensitive equality andmove_to_end.
5. Explain the difference between assignment, a shallow copy and a deep copy.
Level: Entry. What the interviewer looks for: A clear model of names pointing to objects, and a concrete example with nested data.
How to answer:
- Assignment copies nothing: both names point to the same object.
- A shallow copy (
copy.copy,list(x),x[:],dict.copy()) creates a new outer container that still references the same inner objects. copy.deepcopyrecursively copies nested objects, so changing an inner list in the copy does not affect the original.- Deep copies cost more and can be customized with
__deepcopy__; often immutable data makes copying unnecessary.
6. What is a generator, and when would you use one instead of returning a list?
Level: Mid. What the interviewer looks for: Lazy evaluation, memory use, and the fact that a generator can be consumed only once.
How to answer:
- A function containing
yieldreturns a generator: an iterator that produces values on demand and pauses between them. - Use one for large or unbounded streams (reading a big file line by line, paging an API) to keep memory flat.
- A generator is single-pass: once exhausted it yields nothing more, so materialize to a list if you need to iterate twice.
- Generator expressions
(x * 2 for x in data)are the lazy counterpart of list comprehensions.
7. How does a decorator work? Describe one you have written.
Level: Mid. What the interviewer looks for: Understanding that a decorator is a callable that takes a function and returns a replacement, plus functools.wraps.
How to answer:
@decoratorabovedef fis shorthand forf = decorator(f).- A typical decorator defines an inner wrapper taking
*args, **kwargs, adds behavior (timing, retries, logging, auth) and calls the original. - Use
functools.wrapsso the wrapper keeps the original name, docstring and signature metadata. - Decorators with arguments add one more layer: a function that returns the decorator.
8. What problem does a context manager solve, and how do you write one?
Level: Mid. What the interviewer looks for: Guaranteed cleanup even when exceptions occur, and both ways to implement one.
How to answer:
- The
withstatement guarantees setup and teardown (closing files, releasing locks, rolling back transactions) even if the block raises. - Class form: implement
__enter__and__exit__; returning True from__exit__suppresses the exception, so normally return False or None. - Function form:
@contextlib.contextmanagerwith a singleyieldwrapped in try/finally.
9. What is the GIL, and how does it affect threads in Python?
Level: Mid. What the interviewer looks for: Accurate scope: CPython only, CPU-bound versus I/O-bound, and awareness of the optional free-threaded build without overstating it.
How to answer:
- In standard CPython the Global Interpreter Lock lets only one thread execute Python bytecode at a time.
- Threads still help I/O-bound work because the lock is released while waiting on I/O; CPU-bound work needs processes (
multiprocessing,ProcessPoolExecutor) or native extensions that release the GIL. - Since Python 3.13, CPython offers a separate, optional free-threaded build (PEP 703) that can run without the GIL; the default build still has it, and extension compatibility should be checked.
- The GIL does not make your code thread-safe: compound operations still need locks.
10. When would you choose threads, processes or asyncio?
Level: Mid. What the interviewer looks for: Matching the tool to I/O-bound versus CPU-bound work and to the libraries in use.
How to answer:
- asyncio: many concurrent I/O-bound tasks (network calls, sockets) using async-aware libraries, all in one thread.
- Threads: I/O-bound work with blocking libraries, or a small number of background tasks.
- Processes: CPU-bound work that needs multiple cores; data must be picklable and there is startup and IPC cost.
- Mention
concurrent.futuresas a common interface for thread and process pools.
11. Explain how async and await work, and what happens if you call a blocking function inside a coroutine.
Level: Mid. What the interviewer looks for: Cooperative multitasking on an event loop and the blocking-call trap.
How to answer:
async defdefines a coroutine;awaitsuspends it until the awaited operation is ready, letting the event loop run other tasks.- Run concurrent work with
asyncio.gatheror, from Python 3.11,asyncio.TaskGroup, which cancels sibling tasks if one fails. - A blocking call (for example
time.sleepor a synchronous HTTP client) freezes the whole loop; use the async equivalent orasyncio.to_thread.
12. What do dataclasses give you, and which options do you use most?
Level: Mid. What the interviewer looks for: Knowing what is generated and the practical options, not just the decorator name.
How to answer:
@dataclassgenerates__init__,__repr__and__eq__from annotated fields.frozen=Truemakes instances immutable (and hashable wheneqis also true);slots=True(3.10+) reduces memory and blocks new attributes.- Use
field(default_factory=list)for mutable defaults;order=Trueadds comparison methods. - For validation of external input, many teams use a library such as Pydantic instead.
13. Are type hints enforced at runtime? How do you use them on a team?
Level: Mid. What the interviewer looks for: Hints are not enforced by the interpreter; value comes from static checkers and editors.
How to answer:
- No: CPython stores annotations but does not check them; a static checker such as mypy or pyright does.
- Run the checker in CI and tighten settings gradually on an existing codebase.
- Modern syntax: built-in generics (
list[int]), unions with|(3.10+), and in 3.12 thetypealias statement anddef first[T](xs: list[T]) -> Ttype-parameter syntax.
14. Walk me through try / except / else / finally. What makes exception handling good or bad?
Level: Entry. What the interviewer looks for: Correct flow of each clause and judgment about catching narrowly.
How to answer:
elseruns only if the try block raised nothing;finallyalways runs, for cleanup.- Catch the narrowest exception you can handle; avoid bare
except:because it also catchesKeyboardInterruptandSystemExit. - Use
raise NewError(...) from errto keep the original cause; log once, at the level that handles it. - Python 3.11 added exception groups and
except*for handling several errors raised together, for example from a TaskGroup.
15. What do *args and **kwargs do, and what are keyword-only and positional-only parameters?
Level: Entry. What the interviewer looks for: Packing and unpacking, plus the * and / markers in signatures.
How to answer:
*argscollects extra positional arguments into a tuple;**kwargscollects extra keyword arguments into a dict.- Parameters after a bare
*are keyword-only; parameters before/(3.8+) are positional-only. - The same operators unpack at call sites:
f(*items, **options).
16. How does Python resolve variable names, and what is a closure?
Level: Mid. What the interviewer looks for: The LEGB rule and the nonlocal / late-binding details.
How to answer:
- Names resolve Local, Enclosing, Global, then Built-in (LEGB).
- A closure is an inner function that keeps access to variables from the enclosing scope after that scope has returned.
- Assigning to an enclosing variable needs
nonlocal(orglobalfor module level). - Closures bind variables, not values: lambdas created in a loop all see the loop variable’s final value unless you bind it, for example with a default argument.
17. How does CPython manage memory?
Level: Senior. What the interviewer looks for: Reference counting plus the cyclic garbage collector, and practical consequences.
How to answer:
- Every object has a reference count; when it drops to zero the object is freed immediately.
- A cyclic garbage collector finds groups of objects that reference each other but are unreachable.
- Leaks in practice usually come from lingering references (global caches, unbounded lists);
tracemallocandweakrefhelp diagnose and avoid them.
18. What is the difference between an iterable and an iterator?
Level: Mid. What the interviewer looks for: The iterator protocol and why a list can be looped over many times but an iterator cannot.
How to answer:
- An iterable has
__iter__and returns a fresh iterator each time (lists, dicts, files). - An iterator has
__next__and raisesStopIterationwhen done; its__iter__returns itself. - A
forloop callsiter()on the iterable, thennext()untilStopIteration.
What practical Python questions should you expect?
These move from the language to the work: testing, environments, performance and building services.
19. How do you structure tests with pytest? Explain fixtures and parametrize.
Level: Mid. What the interviewer looks for: Practical testing habits, not just tool names: isolation, readable tests, and mocking only at boundaries.
How to answer:
- Plain
assertstatements intest_*functions; pytest rewrites asserts to show helpful failure details. - Fixtures provide setup and teardown through dependency injection, with scopes (function, module, session);
yieldfixtures handle cleanup. @pytest.mark.parametrizeruns one test over many inputs; built-ins liketmp_pathandmonkeypatchcover files and environment.- Mock external boundaries (HTTP, time, payment APIs), not your own internals.
20. How do you manage dependencies and environments for a Python project?
Level: Entry. What the interviewer looks for: Isolation per project and reproducible installs.
How to answer:
- One virtual environment per project (
python -m venv .venv), never installing project packages into the system Python. - Declare dependencies in
pyproject.tomland pin exact versions with a lock file (pip-tools, Poetry, uv or similar) for reproducible builds. - Pin the Python version used in CI and containers so local and production match.
21. A Python function is too slow. How do you find out why and speed it up?
Level: Senior. What the interviewer looks for: Measure first, then fix the biggest cost; algorithmic fixes before micro-optimizations.
How to answer:
- Profile before changing anything:
cProfile, a sampling profiler such as py-spy, ortimeitfor small snippets. - Fix algorithms and data structures first (a set for membership checks instead of a list, avoiding repeated work, caching with
functools.cache). - Then consider vectorizing with NumPy or pandas, batching I/O, or moving hot paths to processes or native code.
- Re-measure to confirm the improvement and add a test so it does not regress.
22. You are building a REST API in Python. How do you choose a framework and structure the project?
Level: Mid. What the interviewer looks for: Trade-offs between frameworks and a sensible layering of code, not loyalty to one tool.
How to answer:
- Pick by need: Django for a full-featured app with an admin and ORM; FastAPI for typed, async-friendly APIs; Flask for small, minimal services.
- Separate routing, business logic and data access so logic can be tested without HTTP.
- Validate input at the boundary, return consistent error shapes, and add logging, timeouts and health checks from the start.
Which behavioral questions do Python developers get?
Answer these with a real example in the STAR shape: situation, task, action, result. Keep the technical detail, because interviewers use these stories to judge depth.
23. Tell me about a production bug in a Python service that you diagnosed. How did you find the root cause?
Level: Mid. What the interviewer looks for: A specific, structured story (situation, task, action, result) that shows systematic debugging and a lasting fix.
How to answer:
- Situation and impact: what broke, who was affected, how you found out.
- Actions: reproducing it, reading logs and tracebacks, narrowing with tests or bisecting, the actual root cause.
- Result: the fix, the regression test you added, and what monitoring or process changed afterwards.
24. Describe a time you disagreed with a reviewer about your code. What happened?
Level: Mid. What the interviewer looks for: Openness to feedback, arguing with evidence rather than ego, and a resolution.
How to answer:
- Briefly state both positions and why each was reasonable.
- Explain how you resolved it: data, a small benchmark, team conventions, or a third opinion.
- Close with the outcome and what you would do the same or differently.
25. Tell me about a time you had to learn a new library or framework quickly to deliver something.
Level: Entry. What the interviewer looks for: A repeatable learning approach and delivering something that worked.
How to answer:
- The deadline and why the new tool was needed.
- How you learned: official docs and tutorials, a small spike project, reading source or tests, asking an experienced colleague.
- What you delivered and what you would now teach someone else about the tool.
26. Give an example of explaining a technical problem or trade-off to a non-technical stakeholder.
Level: Mid. What the interviewer looks for: Translating technical detail into impact, options and a recommendation.
How to answer:
- Who the stakeholder was and what decision they needed to make.
- How you framed it in their terms: risk, time, cost, user impact, with two or three clear options.
- The decision reached and how you confirmed they understood it.
How should you answer situational Python questions?
These are hypothetical. Say what you would do first, why, and who you would involve.
27. You inherit a large, untested Python module that everyone is afraid to touch. How do you start improving it?
Level: Senior. What the interviewer looks for: Safety first: characterization tests and small, reversible steps rather than a rewrite.
How to answer:
- Add characterization tests that pin down current behavior before changing anything.
- Refactor in small steps, each shipped and reviewed: extract functions, add type hints, remove dead code.
- Prioritize the parts that change most often or cause incidents, and agree the plan with the team.
28. Your feature is due tomorrow and you realize the clean solution needs three more days. What do you do?
Level: Mid. What the interviewer looks for: Early, honest communication and a conscious trade-off with the debt recorded.
How to answer:
- Tell your lead or product owner now, with the options and the risks of each.
- Options might be a reduced scope, a safe interim solution behind a feature flag, or moving the date.
- If a shortcut ships, record the follow-up work as a ticket with an owner so the debt is visible.
29. A test in CI fails roughly one run in ten. How would you handle it?
Level: Mid. What the interviewer looks for: Treating flakiness as a real bug, with a method for isolating the cause.
How to answer:
- Do not just add retries; reproduce by running the test repeatedly and in random order (for example with a plugin such as pytest-randomly).
- Common causes: shared state between tests, time and time zones, ordering of unordered data, network calls, race conditions.
- Quarantine it with a visible ticket if it blocks others, then fix the root cause.
30. Your service receives user-uploaded files and query parameters. What security risks do you watch for in Python code?
Level: Senior. What the interviewer looks for: Concrete Python-specific risks and their standard mitigations.
How to answer:
- Never
evalorexecuser input; never unpickle untrusted data (picklecan execute code); useyaml.safe_load, notyaml.load, for YAML. - Use parameterized queries or an ORM to prevent SQL injection; avoid
shell=Truewith user input insubprocess. - Validate file types and sizes, and sanitize file paths to prevent path traversal.
- Keep dependencies patched and scan them in CI.
How should you prepare for a Python interview?
| When | What to do | Why it helps |
|---|---|---|
| 1 week before | Review the core topics above and write small examples for each: a generator, a decorator with functools.wraps, a context manager, a dataclass. Solve a few timed problems and write pytest tests for them. | Explaining behavior you have just run yourself is far more convincing than reciting definitions. |
| 1 week before | Prepare four or five STAR stories: a production bug, a code review disagreement, a deadline trade-off, learning something fast. | One well-prepared story can answer several behavioral questions. |
| 1 day before | Re-read the job ad and map its stack (Django, FastAPI, pandas, asyncio) to your examples. Check your editor, microphone and internet if the interview is remote. | You can steer answers toward the tools the team actually uses. |
| During the interview | Clarify the question, think aloud, state assumptions such as the Python version, and test edge cases before saying you are done. | Interviewers score reasoning and communication, not just the final answer. |
Where can you practice these Python questions?
Use the free mock interview practice tool, already set to Python, to answer timed questions and score yourself against a rubric for structure, relevance and depth. To build your own set of questions by level and type, open the interview question generator for Python.
How can Perimattic AI Interview help you prepare?
Perimattic AI Interview runs conversational mock interviews by role and level, with spoken or typed answers and feedback on each answer against a rubric for structure, relevance and depth. Hiring teams can run structured first-round interviews with the same questions for every candidate, with recorded answers and transcripts for human reviewers. People, not the AI, make hiring decisions.
Get started: Sign up and our team will walk you through Perimattic AI Interview for the way you prepare for or run interviews.
More interview questions
Python interviews, answered
Which Python version should I prepare for?
Prepare for a current version, Python 3.12 or later, and know the features that changed recently: the match statement (3.10), exception groups and TaskGroup (3.11), the new type-parameter syntax (3.12) and the optional free-threaded build (3.13). If the job ad names an older version, check what differs there too.
Do Python interviews include live coding?
Many do. Expect either a short problem solved in a shared editor or a take-home task, followed by questions about your choices. Practice writing clean code out loud, testing edge cases as you go, and explaining time and memory complexity. The conceptual questions on this page often come up while discussing your solution.
How should I answer salary questions in a Python interview?
This page does not quote salary figures, because pay varies widely by city, company and experience. Research current ranges for the role and location from recent job postings and salary surveys, give a range rather than a single number, and tie it to the scope of the role. You can also ask for the budgeted range first.
Want to rehearse Python interviews out loud?
Sign up to tell us how you prepare for or run interviews, and our team will get in touch to walk you through Perimattic AI Interview.
Sign up