python coding interview questions prepared as a printed exercise booklet with separate test sheets
Blog/8 Python Coding Questions to Practise With Tests and Follow-Ups
Shayan Naji

Shayan Naji

10 min read

8 Python Coding Questions to Practise With Tests and Follow-Ups

Practise Python coding interview questions by writing a working solution, explaining its cost, and testing the assumptions that could break it. The eight exercises below cover dictionaries, strings, grouping, generators, intervals, and common mutation bugs. Each includes a follow-up so you can practise adapting your reasoning when the interviewer changes the requirement.

What should you clarify before writing Python code?

Ask what the input contains, what the output should look like, and whether you may change the input. Agree on empty inputs, duplicates, and missing answers before choosing a data structure. A solution can be logically correct and still fail the task because you returned values when the interviewer requested indices.

Use one small example to confirm the contract, then describe the simplest correct approach. Explain an improvement only when it serves the constraints. For the exercises here, assume ordinary Python 3, integer arrays where stated, and strings treated as sequences of code points. Human-language text may need additional rules for accents and normalization.

Keep a printed input sheet beside your practice area, leaving room to write the expected result before running the code. That gives you an independent check instead of treating whatever the interpreter prints as correct. Our live coding interview guide covers the wider conversation around planning, testing, and recovering from a failed attempt.

1. How do you remove duplicates while preserving order?

Return the first occurrence of each hashable value. For example, an input containing repeated user IDs should retain their original arrival order rather than sort them. A set records membership while a list records the answer.

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([]) == []

Say why converting directly to a set loses the required sequence. Under average hash-table behavior, this approach takes O(n) time and O(k) extra storage for k distinct values, including the returned list. It doesn't mutate the input.

The follow-up is: what if values are dictionaries? They aren't hashable, so ask whether uniqueness means the same object, the same full contents, or a matching ID field. If the contract specifies an ID, store that ID in the set. Don't silently convert the whole object to a string and assume you've defined equality correctly.

2. How do you find the first character that appears once?

Count occurrences, then scan the original string to preserve its order. For this exercise, uppercase and lowercase are different and whitespace counts as a character. Return None when no unique character exists.

from collections import Counter

def first_unique(text):
    counts = Counter(text)
    for char in text:
        if counts[char] == 1:
            return char
    return None

assert first_unique('swiss') == 'w'
assert first_unique('aabb') is None
assert first_unique('') is None

The invariant is that the counts describe the complete input before you select an answer. A character that looks unique halfway through may appear again later. The two passes take O(n) time, with O(k) storage for distinct characters.

Ask whether the follow-up requires an index instead of a character. If so, use enumerate in the second pass and return its index. If the input is a live stream, explain that a final answer may change as new characters arrive; the original two-pass contract no longer applies unchanged. Python's Counter documentation explains its counting behavior.

3. How do you find two indices whose values sum to a target?

Use a dictionary of values already visited. Before storing the current value, look for its complement. This order prevents using the same array element twice while still allowing two separate equal values.

def two_sum(numbers, target):
    seen = {}
    for index, value in enumerate(numbers):
        complement = target - value
        if complement in seen:
            return (seen[complement], index)
        seen[value] = index
    return None

assert two_sum([3, 3], 6) == (0, 1)
assert two_sum([2, 7, 11], 9) == (0, 1)
assert two_sum([3], 6) is None

Clarify that any valid pair is acceptable and None represents no solution. Average time is O(n), and storage is O(n). Negative numbers don't require a separate algorithm.

For the follow-up, ask whether the input is already sorted. Two pointers can then use O(1) auxiliary storage. Sorting an unsorted input changes index positions, so that shortcut needs extra bookkeeping if original indices remain part of the contract. Compare this language-specific solution with the equivalent exercise in our Java coding questions if you're switching interview languages.

4. How do you group anagrams without losing duplicates?

For lowercase English words, sorted letters make a clear grouping key. Keep repeated words because the task groups input entries rather than unique vocabulary. This version also groups empty strings together.

def group_anagrams(words):
    groups = {}
    for word in words:
        key = ''.join(sorted(word))
        groups.setdefault(key, []).append(word)
    return list(groups.values())

assert group_anagrams(['eat', 'tea', 'bat']) == [
    ['eat', 'tea'], ['bat']
]
assert group_anagrams(['', '']) == [['', '']]

Explain whether group order matters. Here, groups appear in the order their keys are first encountered, and words retain their input order within each group. Python dictionaries preserve insertion order, as the data structures tutorial describes.

With n words of maximum length m, sorting keys takes O(n m log m) time in the usual worst-case bound. Stored keys and output references add storage proportional to the input's size. A fixed 26-count tuple can avoid sorting when the lowercase-English restriction is guaranteed. Don't claim that optimization supports arbitrary Unicode text without defining how characters map to counts.

5. How do you merge overlapping intervals safely?

Assume closed intervals with start less than or equal to end, and merge intervals that touch. Sorting produces an order in which you only need to compare the next start against the current merged end. Construct fresh output lists so the caller's intervals aren't modified.

def merge_intervals(intervals):
    merged = []
    for start, end in sorted(intervals):
        if not merged or start > merged[-1][1]:
            merged.append([start, end])
        else:
            merged[-1][1] = max(merged[-1][1], end)
    return merged

assert merge_intervals([[5, 7], [1, 3], [3, 6]]) == [[1, 7]]
assert merge_intervals([]) == []

The sorted scan takes O(n) time after O(n log n) sorting; the sorted copy and output require O(n) space. Try a nested interval such as [1, 10] followed by [2, 3] to check that the end never shrinks.

The follow-up changes the intervals to half-open ranges. Touching ranges needn't overlap under that definition, so decide whether adjacency should still merge. State the policy first, then adjust the comparison. Also ask whether invalid ranges should raise an error or be rejected earlier rather than quietly swapping their endpoints.

6. How do you process values lazily with a generator?

Write a generator that yields squares of nonnegative numbers. It should consume the source only as the caller requests results, which is useful when the input is large or arrives incrementally.

def nonnegative_squares(values):
    for value in values:
        if value >= 0:
            yield value * value

result = nonnegative_squares(iter([-2, 0, 3]))
assert next(result) == 0
assert list(result) == [9]
assert list(result) == []

The last assertion exposes an important detail: a generator is exhausted after consumption. Calling the function again creates a new generator, but a previously exhausted input iterator won't magically refill.

Processing n values takes O(n) time under constant-cost arithmetic, with O(1) extra generator state excluding the input and any results the caller collects. Wrapping the generator in list materializes its output and changes the memory story. For arbitrary-size integers, multiplication cost also depends on their bit length.

Ask the interviewer how malformed values should be handled. A broad exception handler that silently skips every error could conceal upstream bugs. Agree on validation or a specific rejection policy instead.

7. Why does a mutable default argument leak data between calls?

Consider a helper intended to collect interview practice tags. Defining its parameter as tags=[] creates one default list when the function is defined, so later calls can share earlier mutations. Use None to request a fresh list, while preserving a deliberately supplied list.

def add_tag(tag, tags=None):
    if tags is None:
        tags = []
    tags.append(tag)
    return tags

assert add_tag('arrays') == ['arrays']
assert add_tag('strings') == ['strings']
existing = []
assert add_tag('tests', existing) is existing

Explain the mutation contract: this implementation appends to a supplied list. If callers expect their list to remain unchanged, copy it or build a new result instead. The fix depends on the intended behavior, not just replacing one syntax pattern.

The follow-up asks whether tags = tags or [] is equivalent. It isn't: an explicitly supplied empty list is falsey, so that expression replaces it. The identity assertion above catches this difference. Python's default argument documentation explains when defaults are evaluated.

8. Why doesn't a shallow copy isolate nested changes?

Shallow copy reference sketch showing two outer lists sharing one inner list

A new outer list can still refer to the same inner lists. Trace the references before changing the code, then decide how much copying the actual data requires.

original = [[1], [2]]
shallow = original.copy()
shallow[0].append(9)
assert original == [[1, 9], [2]]

independent = [row.copy() for row in original]
independent[0].append(7)
assert original == [[1, 9], [2]]

Copying each row works for this two-level structure of lists containing immutable integers. It doesn't promise independence for deeper nested mutable objects. Ask whether deep copying is appropriate or whether an immutable representation would better fit the task.

Distinguish equality from identity during the explanation. Two lists can contain equal values while remaining different objects; two variable names can also refer to exactly the same object. This is a useful place to explain why an unexpected mutation occurs rather than merely naming shallow and deep copies.

Which Python concepts should you review around these exercises?

Start with the concepts that explain your code: list versus tuple mutability, hashability, comprehensions, iterators, exception boundaries, and function scope. Be ready to explain when a small named helper is clearer than a lambda and how positional and keyword arguments reach that helper.

For backend roles, add context managers for reliable resource cleanup, decorators that wrap behavior, and instance versus class-level state. Review modules, packages, and isolated environments so you can explain how you'd run your solution reproducibly. Connect memory questions to retained references rather than assuming every unused object disappears immediately.

Concurrency questions need runtime context. Ask which Python implementation and build the interviewer means before making claims about the GIL; the threading documentation explains the build-dependent limits. Discuss CPU-bound work separately from waiting on network or disk operations. These are conceptual follow-ups to coding practice; prioritize the job description rather than turning tonight's preparation into a tour of every Python feature.

How can you turn these questions into a 45-minute mock?

Python coding mock interview with a partner holding the exercise sheet

Choose one dictionary problem and one mutation or generator problem without opening their solutions. Ask a partner to keep the input sheet and reveal one changed requirement after your first working answer. A blank sheet for expected outputs helps keep the test honest.

  1. Spend five minutes confirming inputs, outputs, and constraints aloud.
  2. Spend twenty minutes implementing the two selected exercises.
  3. Spend ten minutes testing empty, repeated, and boundary inputs, then handle the changed requirement.
  4. Spend ten minutes explaining complexity and reviewing the first point where your reasoning broke.

Score correctness, explanation, testing, and adaptation from zero to two each. Zero means missing, one means completed after help, and two means independently demonstrated. This is a practice rubric, not an employer's hiring threshold. Repeat the weaker exercise with a fresh input before moving to another topic.

If your partner tends to rescue you too quickly, agree that they should ask a question before offering a solution. Our pair programming interview tips show how to use feedback while keeping ownership of your reasoning.

Hiintly can surface live suggestions during a permitted practice conversation, but first attempt the exercise yourself and then check any proposed answer against your tests. Its free 10-minute session resets after a 5-minute cooldown, which fits a short explanation-and-retest drill. For an actual assessment, follow the employer's rules on outside assistance and ask when the policy is unclear.

Finish by writing one specific correction, such as checking the complement before storing the current index. That gives your next practice session a concrete target and makes progress easier to see than simply counting completed questions.

Frequently Asked Questions

Which Python coding interview questions should I practise first?
Start with ordered deduplication, character counts, pair search, and grouping. Then practise generators and mutation bugs so you can explain Python behavior as well as solve algorithms.
Can I use Python built-ins in a coding interview?
Ask what the interviewer permits. Explain what a built-in does and its cost, and be ready to implement the underlying step when that is the skill being tested.
Should I memorize Python interview solutions?
Learn the invariant, data structure, and failure cases. Retest yourself with changed inputs or requirements so you can adapt rather than repeat code you remember.
How do I explain complexity for dictionary solutions?
State the average hash-table assumption, count passes through the input, and include stored keys and output when discussing memory. Avoid presenting average behavior as an unconditional worst-case guarantee.
How should I prepare the night before a Python interview?
Run a short mock with two representative exercises, check the permitted Python environment, and review your own mistakes. Focus on clear explanations and tests rather than adding a large new question list.

Ready To Ace Your Next Interview?

Get undetectable support and personalized guidance to ace live interviews with confidence.