Python Developer Interview Questions with Answers
An open guide to preparing for a Python interview: start at your level, answer out loud and check your conclusions on small examples. Levels indicate the depth of the discussion, not universal requirements of every employer.
CPython 3.12; SQL examples are checked separately on SQLite/PostgreSQL with the stated limitations.
Questions and answers
Junior: fundamentals
CollectionsHow is a list different from a tuple?
A list lets you change what it contains: add, remove and replace values. A tuple fixes its sequence of references once it is created. An object inside a tuple can still be mutable, though: a tuple that holds a list does not become deeply immutable. The choice follows the meaning of the data: a sequence of results is convenient to accumulate in a list, while a fixed pair of coordinates is better returned as a tuple. Whether a tuple is hashable depends on all of its elements, so not every tuple can serve as a dictionary key.
- Example
- The pair (10, 20) can be a dictionary key; ([10], 20) contains a list and is not hashable.
- Common mistake
- Assuming a tuple automatically makes every nested object immutable.
- Interviewer follow-up
- What happens when you modify a list inside a tuple?
ObjectsWhat does assignment mean in Python?
A name is bound to an object; it does not get an independent copy of the object's contents. After b = a, both names can point to the same list. A change to that list through either name is visible through the other, while rebinding b to a new object does not change a. To answer well, it helps to draw the names and the references. The difference between mutating an object and rebinding a name explains many bugs with function arguments and shared settings.
- Example
- After a = [1]; b = a; b.append(2), both names show [1, 2].
- Common mistake
- Expecting a plain assignment to copy the list.
- Interviewer follow-up
- How does a shallow copy differ from deepcopy for a nested structure?
ComparisonHow is is different from ==?
The is operator checks whether two expressions refer to the same object, while == invokes value comparison. For None you write is None: what you need here is a check for one special singleton object. Equal lists can be different objects. The results of is for small numbers or strings may depend on interning and on the implementation, so you cannot build checks of user data on them.
- Example
- Two separately created lists [1, 2] are equal with == but need not be identical with is.
- Common mistake
- Comparing strings with is because a short example happened to work once.
- Interviewer follow-up
- Which class methods take part in an equality check?
FunctionsWhy is a mutable default argument dangerous?
A default argument value is evaluated when the function is defined. The same list is then reused across calls whenever the caller does not pass an argument of its own. If the function appends elements, state accumulates unexpectedly. The usual fix is None in the signature and creating a new list inside the call. You also need to agree explicitly that None is not itself a valid value for the task.
- Example
- def collect(value, items=None): creates items = [] only when items is None.
- Common mistake
- Clearing the shared list at the end of the function: an exception can leave data in it.
- Interviewer follow-up
- How do you define a separate sentinel if None is an allowed value?
CollectionsHow do you safely get a value from a dictionary?
Accessing d[key] signals a missing key with KeyError and fits cases where the key is required. The get method returns a given default value and is convenient for optional data. It is important to tell a missing key from a stored None: get alone, without a sentinel, is not enough for that. If you only need to check presence, use key in d. The choice of operation should reflect the contract of the input data, not a wish to hide any error.
- Example
- For a required user_id, a missing key is an error in the incoming message; an optional language can have a default value.
- Common mistake
- Replacing every lookup with get and then getting an error much further down the code.
- Interviewer follow-up
- When are defaultdict and setdefault useful?
ExceptionsHow do you handle exceptions without losing the cause?
Catch exceptions where you can recover or add useful context. Choose a specific type instead of a bare except. Inside a handler, a bare raise re-raises the current error, and raise NewError(...) from exc explicitly links the new error to its cause. Releasing a resource is the job of finally or a context manager. Logging the same error at every level is usually unnecessary: it produces several messages about a single failure.
- Example
- A date parsing error can be turned into a clear field error while keeping the original ValueError as the cause.
- Common mistake
- Returning None on any network error and treating it as a missing record.
- Interviewer follow-up
- How do else and finally differ in a try statement?
SequencesWhen should you use a comprehension?
A comprehension works well for a short transformation or filtering of a sequence. A list is built in full, while a generator expression yields values on demand. Several nested loops, side effects and complex branching hurt readability; in that case a plain loop is easier to check. The decision also depends on the amount of data: a generator can save extra memory, but it does not remove the cost of computing each element.
- Example
- [x * x for x in values if x >= 0] picks the non-negative values and builds a list of their squares.
- Common mistake
- Using a comprehension only to call a function for its side effect.
- Interviewer follow-up
- When will a generator expression not reduce the program's total memory?
TestingWhat checks does a simple function need?
Start with the contract: the valid inputs, the result and the behavior on error. Then check the typical case, the boundaries, empty data and special values. It is important to check observable behavior rather than reimplement the algorithm in the test. For collections, clarify order, duplicates and mutation of the input separately. A negative test is useful only when the expected failure is defined: an arbitrary exception does not confirm correct validation.
- Example
- For removing duplicates, check an empty list, a list of identical elements and that the order of first appearance is kept.
- Common mistake
- Checking one happy path and assuming the contract is covered.
- Interviewer follow-up
- What is worth parametrizing, and what should stay a separate test?
Middle: putting them into practice
IteratorsHow is an iterable different from an iterator?
An iterable can provide an iterator through iter(). An iterator keeps the iteration state and returns the next value through next() until StopIteration is raised. A list usually lets you start a new pass, but a particular generator cannot simply be restarted once it is exhausted. When you pass an iterator to a library function, find out whether it will consume it entirely: reading it again may return an empty result.
- Example
- After list(iterator), the same iterator is usually exhausted, while the original list remains available.
- Common mistake
- Iterating over a generator twice and expecting the same data.
- Interviewer follow-up
- How do you build an object where every iter() starts a new pass?
GeneratorsWhat does a generator keep between yield statements?
A generator suspends the function and keeps the local state it needs to resume. This lets you process items gradually without collecting the whole result. Laziness also moves errors: an exception may be raised on a later next() call rather than when the generator is created. If a generator holds a file or a connection, you need to plan for closing it in time, especially when the iteration stops early.
- Example
- Reading the lines of a large file with a generator does not require loading the whole file into a list.
- Common mistake
- Treating a lazy expression as a data check that has already run.
- Interviewer follow-up
- How does a consumer that stops early affect releasing the resource?
FunctionsHow does a decorator work, and why use wraps?
A decorator takes a function and returns an object that will be used under its name. A wrapper can add timing, an access check or a request retry, but it must preserve the contract of the arguments and the result. functools.wraps copies important metadata of the original function and sets the __wrapped__ reference. For an async function, the wrapper must also await the result correctly; an ordinary synchronous wrapper does not make a network call asynchronous.
- Example
- A timing decorator should use try/finally if calls that raise must be measured too.
- Common mistake
- Losing the function's name and docstring or swallowing its exceptions.
- Interviewer follow-up
- How does the order of two decorators change the way they work?
ResourcesWhat does with guarantee?
A context manager defines how you enter and leave the scope where a resource is used. Both on normal completion and on an exception, Python calls the exit, which helps close a file, release a lock or finish a transaction. This is not a promise of recovery after the process crashes. The __exit__ method can suppress an exception by returning a true value, so such behavior must be deliberate. For asynchronous release, use async with.
- Example
- with open(...) closes the file even when parsing a line inside the block fails.
- Common mistake
- Thinking that with automatically makes all operations atomic.
- Interviewer follow-up
- How does a transaction manager differ from a connection manager?
TypingAre type annotations checked at runtime?
Plain annotations do not by themselves prevent passing a value of another type. They are used by static analyzers, the editor and libraries that perform validation explicitly. Static checking helps find inconsistent contracts, but it does not replace validating external JSON or data from the database. In an interview, it helps to separate three levels: type hints, runtime checks and domain constraints.
- Example
- The parameter age: int does not forbid a negative age and does not reject a string on its own.
- Common mistake
- Treating a successful type check as proof that an external API payload is correct.
- Interviewer follow-up
- When should you use Protocol instead of inheriting from a common class?
AsynchronyWhy doesn't async def make any code non-blocking?
A coroutine gives control back to the event loop at await points that can actually suspend it. A synchronous network read, time.sleep and long computations inside async def still block the loop's thread. For I/O you need an asynchronous client, or you move the blocking call into a separate thread. For heavy CPU work, consider processes and specialized libraries separately. Many tasks do not mean unlimited throughput of an external service.
- Example
- Replacing time.sleep with await asyncio.sleep lets other tasks do work during the wait.
- Common mistake
- Calling requests inside an async handler and expecting requests to be served concurrently.
- Interviewer follow-up
- How do you limit the number of requests running at the same time?
SQLHow is LEFT JOIN different from INNER JOIN?
INNER JOIN keeps only the matched pairs. LEFT JOIN keeps the rows of the left table and fills in NULL on the right when there is no match. A condition on the right table in WHERE can then remove those rows and effectively change the intended semantics. With a one-to-many relationship, the result contains several rows for one object on the left. So before aggregating, you need to understand the cardinality and decide separately whether you count rows, objects or non-null values.
- Example
- A list of all users with their order counts needs LEFT JOIN and COUNT(order.id), not COUNT(*).
- Common mistake
- Moving a filter on the right table from ON to WHERE without checking the rows with NULL.
- Interviewer follow-up
- How do you select the users who have no orders at all?
ObjectsWhen is a shallow copy not enough?
A shallow copy creates a new outer container but keeps references to the nested objects. That is enough if the nested values are immutable or shared on purpose. When a nested list is edited independently, such a copy unexpectedly changes the original as well. deepcopy copies the object graph more deeply, but it does not automatically settle questions of external resources, identity and cost. Sometimes it is better to build a new domain structure explicitly.
- Example
- With copy = [row[:] for row in matrix] the rows are independent, but deeper nesting still needs analysis.
- Common mistake
- Applying deepcopy to an entire service object instead of finding out who owns the state.
- Interviewer follow-up
- How do you avoid copying a large structure for a small edit?
Senior: trade-offs and reliability
ParallelismWhat does the GIL limit in standard CPython 3.12?
In standard CPython 3.12, the GIL limits simultaneous execution of Python code by threads of one interpreter. So adding threads usually does not speed up a purely computational Python loop. While waiting for I/O and in some extensions the lock can be released, so threads remain useful. This is a property of a specific implementation and version: you cannot carry it over to every Python interpreter or special build. The GIL also does not replace synchronization of multi-step application operations.
- Example
- Two threads downloading files can overlap their waiting; two Python loops crunching numbers need to be measured separately.
- Common mistake
- Declaring all code thread-safe just because of the GIL.
- Interviewer follow-up
- When do you choose processes, threads or asyncio?
AsynchronyHow do you design cancellation for a group of tasks?
Cancellation is part of an operation's lifecycle. A task must release its resources correctly in finally and usually re-raise CancelledError. With TaskGroup, an error in one child task cancels the others and waits for them to finish. It is important to distinguish a timeout for a single attempt, a timeout for the whole operation and an external cancellation of the request. After a partial external effect, a retry may be unsafe; this calls for an operation ID and idempotency.
- Example
- If sending a payment completed on the provider's side, a response timeout does not allow you to retry the charge without checking.
- Common mistake
- Swallowing cancellation in a generic handler and leaving background operations running.
- Interviewer follow-up
- How do you set a common deadline for several sequential requests?
PerformanceHow do you find the cause of a slow Python service?
First define a measurable symptom: latency, CPU, memory, the number of errors or the queue length. Then separate waiting for the database and the network from computation, and check a profile under similar load. Optimizing one function may not change the request time if the bottleneck is N+1 queries or a connection limit. After a change, compare the latency distribution and resource usage, not just the luckiest run. Correctness of the result remains a separate criterion.
- Example
- Making serialization 2 ms faster will do little for a request that waits 800 ms for the database.
- Common mistake
- Starting by rewriting everything as async without measuring the cause.
- Interviewer follow-up
- How do you check that a cache has not changed data consistency?
ReliabilityHow do you make retryable job processing safe?
Assume a message can arrive again and the process can stop between the external effect and acknowledging the processing. Choose a stable operation ID and a uniqueness constraint in durable storage. Combine the business state change and recording the outgoing event in one transaction if they live in the same database. An external service needs its own idempotency mechanism or state reconciliation. A single existence check before an insert does not protect against two concurrent handlers.
- Example
- Two requests with the same order key must return one result, not create two charges.
- Common mistake
- Promising exactly-once processing just because the consumer acknowledges messages.
- Interviewer follow-up
- How do you handle an uncertain result of an external HTTP request?
Practical tasks
1. Remove duplicates while keeping order
For a list of hashable values, return the first occurrence of each element. Do not modify the input.
Expected result. [3, 1, 3, 2, 1] → [3, 1, 2]; [] → [].
Solution and explanation
A set stores the values already seen, and a list stores the result in the original order. Expected time is O(n), extra memory is O(k). The hashability requirement is part of the contract.
def unique_in_order(values):
seen = set()
result = []
for value in values:
if value not in seen:
seen.add(value)
result.append(value)
return result
assert unique_in_order([3, 1, 3, 2, 1]) == [3, 1, 2]
assert unique_in_order([]) == []
assert unique_in_order([0, 0]) == [0]2. Yield bounded batches lazily
Write a generator batches(iterable, size) that yields lists no longer than size. Keep the last incomplete batch; size must be positive.
Expected result. range(5), size=2 → [[0, 1], [2, 3], [4]]. An empty input yields no batches.
Solution and explanation
We accumulate only the current batch. Validation in a generator function runs on the first read. Extra memory is O(size), and the source itself is never materialized.
def batches(values, size):
if size <= 0:
raise ValueError('size must be positive')
batch = []
for value in values:
batch.append(value)
if len(batch) == size:
yield batch
batch = []
if batch:
yield batch
assert list(batches(range(5), 2)) == [[0, 1], [2, 3], [4]]
assert list(batches([], 2)) == []3. Limit the concurrency of operations
Run an async handler for every value with no more than limit calls at a time. Keep the order of the results and cancel the group on error.
Expected result. Results come in the input order; no more than limit operations run inside the handler at once.
Solution and explanation
Semaphore limits the active work, and TaskGroup manages the lifecycle of the child tasks. This example creates a task for every input, so a huge stream needs a pool of workers with a bounded queue.
import asyncio
async def bounded_map(values, handler, limit):
if limit < 1:
raise ValueError('limit must be positive')
semaphore = asyncio.Semaphore(limit)
async def run(value):
async with semaphore:
return await handler(value)
async with asyncio.TaskGroup() as group:
tasks = [group.create_task(run(value)) for value in values]
return [task.result() for task in tasks]Seven-day preparation plan
- Write down the job requirements and mark the topics you know and the ones you don't.
- Answer the Junior questions out loud, then check yourself against the explanations.
- Work through the Middle questions. For every mistake, write a small example of your own.
- Solve the practical tasks without hints and check the edge cases.
- Work through the Senior questions and explain the trade-offs as they apply to your project.
- Run a mock interview: clarify the conditions, reason out loud and check your conclusions.
- Go over your mistakes, prepare real stories from your experience and check your equipment.