Python · Interview
Python interview questions
Twenty-five original Python interview questions covering data structures, state, validation, performance, output prediction, debugging and realistic reporting decisions. Try each answer before opening it; runnable snippets are checked during the build and in the browser.
Jump to a question
ConceptJuniorA warehouse records repeated changes to each item. When would you use a dictionary instead of a list of pairs?
Answer
Use a dictionary when the main operation is finding and updating a total by item code: each code maps to one current quantity, so an update is usually constant-time. A list of pairs is useful if event order or duplicate records must be retained, but repeatedly searching that list for a code takes linear time. Keep the input events separately if an audit trail is required; a summary dictionary should not pretend to be that audit trail.
Predict the outputMid-levelWhat does this sorting code print, and why does the tie not preserve the input order?
items = [('tea', 5), ('flour', 5), ('rice', 8)]
print(sorted(items, key=lambda item: (-item[1], item[0])))
Answer
It prints rice first because -8 sorts before -5, then flour before tea because the second key component compares codes alphabetically. The tie does not retain tea before flour: the key explicitly asks for alphabetical ordering, which overrides input order. Python's stable sort matters only when complete sort keys compare equal. This is a useful way to state a business tie-break without a second pass.
It prints
[('rice', 8), ('flour', 5), ('tea', 5)]
CodingMid-levelWrite a function that returns a non-negative restock shortfall from current units, daily demand and lead days; show the result for (7, 3, 4) and (20, 2, 5).
Answer
Required stock is daily demand multiplied by lead days. Subtract current stock and clamp at zero: an item with more than enough stock should not have a negative order quantity. The first item needs twelve units but has seven, so its shortfall is five; the second needs ten but has twenty, so it needs none. In production, validate non-negative inputs and decide how to handle demand forecasts that change over time.
def shortfall(current, daily, days):
return max(0, daily * days - current)
print(shortfall(7, 3, 4))
print(shortfall(20, 2, 5))
Output
5 0
ScenarioSeniorOne warehouse row has a missing lead time. Should a restock report silently assume zero, skip the row or stop?
Answer
Do not silently turn missing lead time into zero: that makes an urgent item appear fully stocked. Agree on a data-quality policy with the report owner. A useful default is to reject or quarantine the row, report its item code and reason, and still compute the valid rows; a critical procurement workflow may instead fail the whole report. Keep rejected-row counts visible, log enough detail for correction, and never mix unknown values with genuine zero-day delivery.
ConceptMid-levelWhat is the time cost of building a dictionary of N stock records and then sorting its items for a report?
Answer
Accumulating N records in a dictionary is O(N) on average, assuming ordinary hash-table behaviour. Sorting K distinct item codes costs O(K log K), so the combined cost is O(N + K log K), with O(K) summary storage. Do not claim that dictionary iteration itself is an alphabetical report: even if insertion order is retained, that order describes input, not the desired ranking. The sort key should also specify how equal shortages are resolved.
ConceptJuniorWhat is the difference between d[key] and d.get(key) when a stock code is absent?
Answer
d[key] raises KeyError when the code is absent, which is useful when missing data should stop a report. d.get(key) returns None, or a supplied default such as zero. Choose deliberately: defaulting a genuinely unknown item to zero can hide a data-quality problem.
ConceptJuniorWhy should a report not print a Python set directly when output order matters?
Answer
A set is for uniqueness and fast membership tests, not a stable presentation order. Its iteration order is not a contractual sorted order and may change across runs. Convert to a sorted list before printing, or retain a separate list when first-seen order matters.
ConceptMid-levelWhen should Python code use is rather than == in a validation branch?
is rather than == in a validation branch?Answer
Use is for identity checks such as value is None, because there is only one None object. Use == for value comparison, including strings, numbers and lists. Two separately created lists can compare equal while not being the same object; relying on identity there is a bug.
ConceptMid-levelWhy is def add(item, bucket=[]) risky for independent requests?
def add(item, bucket=[]) risky for independent requests?Answer
Default arguments are evaluated once when the function is defined, so that list is shared by every call that omits bucket. Later requests can inherit earlier data. Use bucket=None and create a new list inside the function when None is passed.
ConceptMid-levelHow can Python's stable sort help keep an earlier business ordering when ranks tie?
Answer
Python's sort is stable: records whose complete sort keys compare equal keep their input order. That helps when input order is already a meaningful tie-break. If the business wants alphabetical ties, put the name in the key explicitly; stability alone does not provide it.
ConceptMid-levelDoes rows.copy() isolate nested dictionaries inside a Python list?
rows.copy() isolate nested dictionaries inside a Python list?Answer
No. It creates a new outer list but keeps references to the same nested dictionaries. Replacing an element in the copy is isolated, while changing a field of a shared dictionary affects both views. Make explicit nested copies when independent mutable records are required.
ConceptSeniorWhen is a generator preferable to constructing a full list of parsed rows?
Answer
A generator can yield one parsed row at a time, reducing peak memory when the data is large and consumed once. It does not automatically make parsing faster, and a caller that needs random access or repeated passes may need to materialise it. Keep error handling close to the row that failed.
ConceptMid-levelWhy should a parser catch ValueError around integer conversion instead of catching every Exception?
Answer
ValueError is the expected failure for an invalid integer token. Catching every Exception can hide programming bugs, I/O failures or unrelated faults and turn them into plausible but incorrect results. Narrow the try block to the operation you intend to recover from.
ScenarioSeniorAn inventory feed contains a sale larger than recorded stock. Should a report clamp the balance to zero?
Answer
Clamping silently destroys evidence of an inconsistency and makes reconciliation impossible. Report the negative balance or quarantine that row according to an agreed policy, with the SKU and source event visible. A later correction can then be audited; zero should mean a measured zero, not an unknown value.
ScenarioMid-levelA catalogue import repeats a SKU with two different minimum-stock thresholds. What should the program do?
Answer
Reject or flag the duplicate rather than letting the last line win silently. The source needs a clear precedence rule before a report can choose a threshold. If the workflow must continue, quarantine the ambiguous SKU and report the count of excluded rows separately from valid results.
ScenarioMid-levelA checkout report sums thousands of currency values. Why avoid binary floats for the stored amounts?
Answer
Many decimal fractions have no exact binary floating-point representation, so repeated addition can produce a value that rounds unexpectedly. Store whole cents as integers when the currency precision is fixed, or use Decimal with an explicit rounding rule when it is not.
ScenarioSeniorA debug log includes customer names beside failed order rows. How can you keep it useful without leaking data?
Answer
Record a non-sensitive row identifier, error category and enough structural context to reproduce the failure, but omit names and full input payloads by default. Limit access and retention of diagnostic logs. A deliberate opt-in, redacted sample is safer than logging every raw row.
ScenarioMid-levelA report passes tests locally but rows appear in a different order on another machine. What would you change?
Answer
State the ordering contract explicitly and sort at the output boundary using a deterministic key, including tie-breaks. Dictionary insertion order reflects input order, not business ranking. Add tests with shuffled input and equal primary scores so an accidental order cannot pass unnoticed.
ScenarioSeniorA million-row file is imported once to compute per-SKU totals. Would you load all rows first?
Answer
Usually stream and aggregate into a dictionary keyed by SKU. This keeps memory proportional to distinct SKUs rather than every event. Retain raw rows only when an audit trail or second pass is required, and validate each row before changing the totals.
ScenarioMid-levelA sensor accepts readings from 0 through 50. Which tests best expose boundary mistakes?
Answer
Test 0 and 50 as accepted values, then -1 and 51 as rejected values; include a malformed token and an all-invalid batch. These distinguish inclusive from exclusive comparisons and check that an empty valid set does not cause division by zero.
Predict the outputMid-levelWhat does this code print after assigning the same list to two names?
values = [1, 2]
alias = values
alias.append(3)
print(values)
Answer
The output is [1, 2, 3] because both names refer to the same list object and append mutates it. Assignment does not create a copy; use values.copy() or a slice when an independent outer list is needed.
It prints
[1, 2, 3]
Predict the outputMid-levelWhat does the following dictionary comprehension print for repeated names?
rows = [('a', 1), ('b', 2), ('a', 3)]
print({name: value for name, value in rows})
Answer
It prints {'a': 3, 'b': 2}. Dictionary keys are unique, so the later tuple for a replaces its earlier value; this comprehension does not add duplicates. Use an accumulation loop when the intended result is a total.
It prints
{'a': 3, 'b': 2}
Predict the outputMid-levelWhat order do these lines print when the function returns inside try?
def read_value():
try:
return 7
finally:
print('cleanup')
print(read_value())
Answer
The function prints cleanup before the caller prints 7. A finally block runs while control leaves the try, including a return path. Avoid returning a different value from finally, which would obscure the original result or exception.
It prints
cleanup 7
CodingMid-levelWrite a function that counts category strings and prints category totals alphabetically for the sample list.
Answer
A dictionary accumulates one count per category. The loop uses get(category, 0) + 1 so repeated values are added, then sorted keys make the report deterministic. The sample has two fruit records and one drink record, so drink prints first alphabetically.
def counts(categories):
result = {}
for category in categories:
result[category] = result.get(category, 0) + 1
return result
for category, total in sorted(counts(['fruit', 'drink', 'fruit']).items()):
print(category, total)
Output
drink 1 fruit 2
Continue learning
Use checked exercises to test the ideas, review a lesson when you need the explanation, then combine the skills in a project.
Expense summary command-line tool
Build a Python command-line expense analyser with validation, category totals, sorting and a reusable report function.
Inventory reconciliation report
Build a Python report that reconciles repeated stock counts with a product catalogue and flags missing, unknown and low-stock items.
How this page was checked. Runnable examples and reference solutions were run with CPython 3.11 at build time; runs in your browser on CPython 3.14 (Pyodide) by the publishing checks, and the output shown is what it printed. The Run buttons execute the same code on your device; the site does not upload your code for execution.