Python interview questions for live coding
Here are 11 practical Python interview questions you can paste into a shared editor, from warm-up to senior. Each has starter code that has been run, what a good answer shows, and one follow-up. They test everyday Python: dicts, iterators, decorators and threads.
Try it in a pad2 free interviews, no card needed.
How to use these
Pick one warm-up and one core or senior question for a 45 minute interview. Paste the code block into a pad before the candidate joins. The lines marked # => show what a correct answer prints, so the candidate can run the file and check their own work.
Some questions are a function to write. Others are working code with a bug, because reading code is most of the job. For how to choose and pace a question, see our guide to technical interview questions.
The questions
1. Most common words Warm-up
Return the n most common words in a text. Ignore case and punctuation. Break ties alphabetically.
def top_words(text, n=3): pass # Examples print(top_words("The cat and the hat. The end!")) # => [('the', 3), ('and', 1), ('cat', 1)] print(top_words("", 2)) # => []A good answer shows: Clean string handling, a dict or Counter, and a sort key with two parts. Watch whether they ask what counts as a word before they type.
Follow-up: The text is now a 2 GB file. What changes?
2. The list that remembers Warm-up
This code runs and prints what the comments say. The author expected the second call to print ["b"]. Ask the candidate to explain the output and fix the function.
def add_tag(tag, tags=[]): tags.append(tag) return tags print(add_tag("a")) # => ['a'] print(add_tag("b")) # => ['a', 'b']A good answer shows: They know a default value is created once, when the function is defined, and they reach for None as the default without being told.
Follow-up: Where else does shared mutable state bite in Python? Class attributes are a good answer.
3. Totals per customer Core
Given a list of orders, return each customer with their total, largest total first.
orders = [ {"customer": "ana", "amount": 30}, {"customer": "bo", "amount": 15}, {"customer": "ana", "amount": 12}, ] def totals(orders): pass # Examples print(totals(orders)) # => [('ana', 42), ('bo', 15)] print(totals([])) # => []A good answer shows: Grouping with a dict or defaultdict in one pass, then sorting by value. This is most of what day-to-day data code looks like.
Follow-up: Two customers have the same total. What order do they come out in, and is that guaranteed?
4. Merge overlapping intervals Core
Given a list of (start, end) pairs in any order, merge the ones that overlap or touch.
def merge(intervals): pass # Examples print(merge([(8, 10), (1, 3), (2, 6), (9, 12)])) # => [(1, 6), (8, 12)] print(merge([(1, 2), (2, 3)])) # => [(1, 3)] print(merge([(1, 10), (2, 3)])) # => [(1, 10)]A good answer shows: Sorting first, then one pass. The third example catches answers that take the end of the later interval instead of the larger end.
Follow-up: Intervals now arrive one at a time and you must answer after each. How would you store them?
5. Batches from any iterable Core
Write a generator that yields lists of up to size items. It must work on a generator, not only on a list.
def batched(items, size): pass # Examples print(list(batched(range(7), 3))) # => [[0, 1, 2], [3, 4, 5], [6]] print(list(batched((c for c in "abcd"), 2))) # => [['a', 'b'], ['c', 'd']] print(list(batched([], 2))) # => []A good answer shows: They understand iterators: no len(), no slicing, and the last short batch is not lost. A stub that returns None fails loudly here, which is a useful first run.
Follow-up: The standard library has itertools.batched since Python 3.12. How does its output differ from yours?
6. Summarise a log Core
Each line is "date time LEVEL message". Count the lines per level and return the first ERROR message, or None. Skip lines that do not parse.
lines = [ "2026-11-02 14:03:11 INFO started", "2026-11-02 14:03:12 ERROR payment timeout", "garbage", "2026-11-02 14:03:15 ERROR card declined", ] def summarise(lines): pass # Examples print(summarise(lines)) # => ({'INFO': 1, 'ERROR': 2}, 'payment timeout') print(summarise([])) # => ({}, None)A good answer shows: split with a limit so the message keeps its spaces, and a calm way of handling bad input. Candidates who reach for a regex should be able to say why.
Follow-up: How would you test this? Ask for three cases they would write first.
7. A retry decorator Core
Write retry(times) so the decorated function is called again when it raises, up to times calls in total. If the last call fails, let its exception through.
def retry(times): pass # Examples calls = 0 @retry(times=3) def flaky(): global calls calls += 1 if calls < 3: raise ValueError("not yet") return "ok" print(flaky(), calls) # => ok 3A good answer shows: Three levels of function, a closure over times, and functools.wraps. The stub fails on the decorator line, so they must read a traceback first.
Follow-up: Retry only on some exception types, and wait longer between attempts.
8. A sliding window rate limiter Core
Allow at most limit calls in any window seconds. allow(now) returns True and records the call, or returns False. Time is passed in, so it is easy to test.
class Limiter: def __init__(self, limit, window): pass def allow(self, now): pass # Examples limiter = Limiter(limit=2, window=10) print(limiter.allow(0)) # => True print(limiter.allow(1)) # => True print(limiter.allow(2)) # => False print(limiter.allow(11.5)) # => TrueA good answer shows: A deque of timestamps, dropping old ones from the left. Good candidates notice that a refused call should not be recorded.
Follow-up: There are a million users, each with their own limit. What does memory look like, and what would you change?
9. An LRU cache Senior
Build a cache with a fixed capacity. get and put are O(1). When it is full, put evicts the entry that was used least recently. get counts as use.
class LRU: def __init__(self, capacity): pass def get(self, key): pass def put(self, key, value): pass # Examples cache = LRU(2) cache.put("a", 1) cache.put("b", 2) print(cache.get("a")) # => 1 cache.put("c", 3) print(cache.get("b")) # => None print(cache.get("a"), cache.get("c")) # => 1 3A good answer shows: They know dicts keep insertion order, or use OrderedDict.move_to_end. Ask them to say why each operation is O(1).
Follow-up: Two threads share this cache. What breaks, and what is the smallest fix?
10. Ten slow calls in under a second Senior
slow() stands in for a network call. Make run() return the results for all inputs, in input order, in well under the 2 seconds a loop would take.
import time def slow(x): time.sleep(0.2) return x * x def run(inputs): return [slow(x) for x in inputs] # Examples start = time.perf_counter() print(run(range(10))) # => [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] print("under 1 s:", time.perf_counter() - start < 1)A good answer shows: ThreadPoolExecutor.map or asyncio, and a clear account of why threads help here even with the GIL. The last line should print True when they are done.
Follow-up: slow() now does heavy arithmetic instead of waiting. Does your answer still help?
11. Make it faster without changing it Senior
This function returns the values that appear more than once. It is too slow on a million items. Speed it up and keep the output exactly the same.
def duplicates(items): result = [] for i in range(len(items)): for j in range(i + 1, len(items)): if items[i] == items[j] and items[i] not in result: result.append(items[i]) return result # Examples print(duplicates([3, 1, 3, 2, 1, 3])) # => [3, 1] print(duplicates([1, 2, 2, 1])) # => [1, 2]A good answer shows: They read before they rewrite. The quick set-based version returns [2, 1] for the second example, because it reports a value at its second sighting. Noticing that is the point.
Follow-up: How would you prove the new version matches the old one on inputs you have not thought of?
Run them with a candidate
Every snippet here runs on Python 3 with the standard library only. If you want a pad that both of you can type in and run, QuizzX is Python0/month per team for unlimited interviews, and the first 2 are free. See the online code editor for interviews page or the pricing.
Questions
- Which Python version do these questions need?
- Any current Python 3. The snippets use only the standard library, and each one has been run.
- Can candidates use the standard library?
- Yes, and you should say so at the start. Knowing that collections.Counter or functools.wraps exists is a fair signal. If you want to see the logic by hand, ask for it as a follow-up.
- How do I judge a Python answer beyond "it works"?
- Look at how they handle the empty input, whether names say what things are, and whether they ran the code before saying it was done. Then ask the follow-up and listen to how they reason.
- Are these suitable for data roles?
- The grouping, log parsing and batching questions are. They use plain Python, so they do not test pandas or SQL.
Read next
- JavaScript interview questions
- Java interview questions
- Technical interview questions
- Online code editor for interviews
- Pricing
Try it in a pad2 free interviews, no card needed.