10 role-specific questions
Python Developer Interview Questions & Answers
Python interviews test fluency with the language — data structures, generators, decorators, common gotchas — plus concurrency, testing and a web framework such as Django, Flask or FastAPI.
Free, no sign-up. 93 questions in this role's practice pool, including behavioural, HR and situational questions.
Python interview questions
Core Python, data structures, generators, decorators, the GIL, async, packaging and web frameworks.
1.
Compare lists, tuples, sets and dictionaries in Python. When would you use each?
BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Choosing the right data structure.
Key points a strong answer covers
- list. Lists are ordered and mutable.
- tuple. Tuples are immutable — good for fixed records and dictionary keys.
- set. Sets hold unique items with fast membership tests.
- dict. Dicts map keys to values with O(1) average lookups (insertion-ordered since 3.7).
- Complexity. Membership: O(1) average in sets/dicts vs O(n) in lists.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Checking membership in a large list inside a loop.
- Using a list where a tuple signals intent better.
Likely follow-up questions
- Why can a tuple be a dictionary key but a list can't?
- How would you remove duplicates while keeping order?
Example strong answer
A list is an ordered, mutable sequence — my default for collections I'll append to or sort. A tuple is ordered but immutable, which suits fixed records like coordinates and function return values, and because it's hashable (if its contents are) it can be a dict key or set member. A set stores unique items and checks membership in O(1) on average, so it's ideal for de-duplicating or testing 'have I seen this id?' — doing that with a list inside a loop is O(n²). A dict maps keys to values with fast lookups and keeps insertion order since Python 3.7. To de-duplicate while keeping order I use
list(dict.fromkeys(items)).2.
What are generators, and why would you use them?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Memory-efficient iteration.
Key points a strong answer covers
- yield. A generator function uses
yieldto produce values one at a time. - Lazy / memory efficient. Values are produced lazily, so large or infinite sequences don't need to fit in memory.
- Iterator protocol. Generators are iterators — they can be consumed once.
- Generator expressions / use cases. Generator expressions; reading large files line by line; pipelines.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Trying to iterate a generator twice.
- Building a huge list just to sum it.
Likely follow-up questions
- What's the difference between
[x for x in y]and(x for x in y)? - What does
yield fromdo?
Example strong answer
A generator is a function that uses
yieldto produce values one at a time. Calling it returns an iterator; eachnext()runs the function until the nextyield, then pauses with its state intact. Because values are produced lazily, you can process huge or even infinite sequences without holding them in memory — reading a 5 GB log file line by line and yielding only the error lines, for example. Generator expressions likesum(x * x for x in numbers)avoid building an intermediate list. They're also nice for pipelines of small steps. A generator can only be consumed once, so iterating it a second time gives nothing.- yield. A generator function uses
3.
What is a decorator in Python? Write or describe one.
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Understanding first-class functions and closures.
Key points a strong answer covers
- Function that wraps a function. A decorator takes a function and returns a new function that wraps it.
- @ syntax.
@decoratoris shorthand forfunc = decorator(func). - functools.wraps.
functools.wrapspreserves the original function's name and docstring. - Use cases. Logging, timing, caching (lru_cache), retries, auth checks, route registration.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Forgetting *args and **kwargs in the wrapper.
- Not using functools.wraps.
Likely follow-up questions
- How would you write a decorator that takes arguments, like @retry(times=3)?
- What does
lru_cachedo?
Example strong answer
A decorator is a function that takes a function and returns a new one, usually wrapping the original to add behaviour before or after it runs.
@timerabove a function is shorthand forfunc = timer(func). A timing decorator defines an innerwrapper(*args, **kwargs)that records the time, calls the original with the same arguments, logs how long it took and returns the result; I decorate the wrapper withfunctools.wraps(func)so the name and docstring survive. Real uses are logging, caching withfunctools.lru_cache, retries with backoff, permission checks like Django'slogin_required, and registering routes in Flask or FastAPI. A decorator with arguments, like@retry(times=3), is a function that returns a decorator.4.
What is the GIL, and how does it affect concurrency in Python?
AdvancedTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Choosing between threads, processes and asyncio.
Key points a strong answer covers
- One thread executes bytecode. In CPython the GIL lets only one thread execute Python bytecode at a time.
- I/O-bound threads still help. The GIL is released during I/O, so threads help I/O-bound work.
- CPU-bound needs processes. For CPU-bound work use multiprocessing or native extensions (NumPy).
- asyncio. asyncio handles many I/O tasks on one thread.
- Free-threaded builds. Python 3.13 introduced an optional free-threaded build (experimental).
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Saying Python can't do concurrency at all.
- Using threads to speed up CPU-bound loops.
Likely follow-up questions
- Would threads speed up resizing 1,000 images in pure Python?
- When would you choose asyncio over threads?
Example strong answer
The GIL — Global Interpreter Lock — in CPython lets only one thread execute Python bytecode at a time, which simplifies memory management but limits parallelism. It's released while a thread waits on I/O, so threads still speed up I/O-bound work like making many HTTP requests. For CPU-bound work in pure Python — heavy loops, parsing — threads don't help; I use
multiprocessingor aProcessPoolExecutor, or libraries like NumPy that do the work in C and release the GIL. For lots of concurrent network I/O, asyncio runs thousands of tasks on one thread. Python 3.13 added an optional free-threaded build without the GIL, but it's still experimental and library support varies.5.
Why is using a mutable default argument like
def f(items=[])a bug?BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Awareness of a classic Python gotcha.
Key points a strong answer covers
- Evaluated once. Default values are evaluated once, when the function is defined.
- Shared between calls. The same list is shared by every call, so it accumulates values.
- Fix with None. Use
Noneas the default and create a new list inside.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Thinking the list is recreated on each call.
- Not knowing the fix.
Likely follow-up questions
- Does the same problem apply to dataclass fields?
- Can this behaviour ever be useful?
Example strong answer
Default argument values are evaluated once, when the function is defined, not each time it's called. So
def add(item, items=[])creates one list that every call shares: the first call returns[1], the next call returns[1, 2], and so on — state leaks between calls. The fix is to useNoneas a sentinel:def add(item, items=None): if items is None: items = []. The same thing applies to dicts and sets, and dataclasses guard against it by requiringfield(default_factory=list). Occasionally people use the behaviour on purpose as a simple cache, butfunctools.lru_cacheis clearer.6.
How does async/await work in Python? When would you use it?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Understanding asyncio's model and limits.
Key points a strong answer covers
- Coroutines & event loop. async def creates coroutines run cooperatively by an event loop.
- await yields control. await suspends the coroutine so others can run while it waits.
- Concurrency. asyncio.gather / TaskGroup run many I/O operations concurrently.
- Blocking calls. A blocking call stalls the whole loop — use async libraries or to_thread.
- Use cases. High-concurrency I/O: APIs, websockets, crawlers.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Calling
requests.getortime.sleepinside async code. - Using async for CPU-bound work.
Likely follow-up questions
- What happens if one coroutine does a blocking database call?
- What does
asyncio.TaskGroupadd overgather?
Example strong answer
async defdefines a coroutine, and an event loop started withasyncio.runruns coroutines cooperatively on a single thread. When a coroutine hitsawaiton something not ready — a network response — it suspends and the loop runs other coroutines, then resumes it when the data arrives. Withasyncio.gatheror aTaskGroup, I can fetch hundreds of URLs concurrently. It shines for I/O-heavy work: API servers with FastAPI, websockets, crawlers. The catch is that everything must be non-blocking: callingrequests.getortime.sleepinside a coroutine freezes the entire loop, so I use async libraries like httpx, or push blocking work toasyncio.to_thread. It doesn't help CPU-bound work.7.
How do you manage dependencies and environments in Python projects?
BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Professional project hygiene.
Key points a strong answer covers
- Virtual environments. Each project gets its own virtual environment.
- Declare dependencies. Dependencies declared in pyproject.toml (or requirements files).
- Lock versions. A lock file pins exact versions for reproducible builds.
- Separate dev deps. Dev/test dependencies kept separate.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Installing packages globally.
- Unpinned dependencies in production.
Likely follow-up questions
- What's the difference between pyproject.toml and a lock file?
- How would you upgrade dependencies safely?
Example strong answer
Every project gets its own virtual environment so its packages don't clash with other projects or the system Python. Dependencies are declared in
pyproject.toml— with ranges for libraries — and a lock file pins exact versions and hashes so every machine and the CI build install the same thing. These days I use uv or Poetry, which handle the environment, resolution and locking together; on older projects, pip-tools generating a pinned requirements file does the same job. Development dependencies like pytest and ruff are kept separate from runtime ones. I upgrade in small batches with Dependabot or Renovate, letting the test suite catch breaking changes.8.
Compare Django, Flask and FastAPI. Which would you choose for a new project?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Framework judgement based on requirements.
Key points a strong answer covers
- Django batteries included. Django is batteries-included: ORM, admin, auth, migrations.
- Flask minimal. Flask is minimal and flexible — you choose the pieces.
- FastAPI typed async APIs. FastAPI is async-first with Pydantic validation and automatic OpenAPI docs.
- Choosing. Choose by needs: full web apps and admin → Django; typed APIs → FastAPI.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Choosing purely on benchmark speed.
- Not mentioning the team's experience.
Likely follow-up questions
- How does FastAPI use type hints for validation?
- What would you add to Flask to match Django's features?
Example strong answer
Django is batteries-included: an ORM, migrations, authentication, an admin site, forms and templating, with strong conventions — great for a full web application or a back office where the admin alone saves weeks. Flask is a microframework: routing and little else, so you choose the ORM, auth and validation — flexible, but you assemble it yourself. FastAPI is built for APIs: async-first, uses type hints and Pydantic for request validation and serialisation, and generates OpenAPI docs automatically. For a new JSON API or microservice I'd lean to FastAPI; for a content- or admin-heavy product, Django — possibly with Django REST Framework. The team's experience weighs heavily too.
9.
How do you test Python code?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Testing practice and tooling.
Key points a strong answer covers
- pytest. pytest is the standard test runner.
- Fixtures. Fixtures provide reusable setup like a test database or client.
- Parametrize.
@pytest.mark.parametrizecovers many cases concisely. - Mocking. Mock external services with unittest.mock or monkeypatch.
- CI / coverage. Run in CI with coverage.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Mocking so much that tests only test the mocks.
- Tests that hit real external APIs.
Likely follow-up questions
- What's the difference between
patchandmonkeypatch? - How would you test code that depends on the current time?
Example strong answer
I use pytest. Fixtures handle setup — a test client, a temporary database, sample data — and live in
conftest.pyso they're shared; their scope controls whether they're rebuilt per test or per session.@pytest.mark.parametrizeruns one test over many inputs, which is perfect for edge cases. External services are mocked at the boundary withunittest.mock.patch,monkeypatch, or HTTP-level tools like respx, while my own code runs for real. For time-dependent code I inject a clock or use freezegun. Everything runs in CI with coverage reporting, and I focus coverage on business logic rather than chasing a number.10.
What's the difference between
==andisin Python?BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Precision about identity vs equality.
Key points a strong answer covers
- == compares values.
==compares values (calls__eq__). - is compares identity.
ischecks whether both names refer to the same object. - Use is for None. Use
isfor singletons like None. - Interning pitfall. Small ints and some strings are cached, so
iscan appear to work by accident.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Using
isto compare strings or numbers. - Writing
== None.
Likely follow-up questions
- Why might
a is bbe True for small integers but False for large ones? - How would you make a class compare by value?
Example strong answer
==checks whether two objects have equal values — it calls__eq__— whileischecks identity: whether both names point to the very same object. Two separate lists[1, 2]are==but notis. The rule is to useisonly for singletons likeNone,TrueandFalse—if result is None— and==for everything else. Comparing numbers or strings withisis a bug that sometimes works by accident, because CPython caches small integers from -5 to 256 and interns some strings, sox is 100can be True whilex is 1000is False.- == compares values.
Ready to answer them out loud?
Run a timed python developer mock interview, type or speak your answers, and get a score breakdown with what to improve.