Python Course · Mistakes lesson

Common Python Interview Mistakes and How to Avoid Them

Fix off-by-one search errors, mutable defaults and empty-input assumptions with small tested fixtures.

Learn the pattern, trace runnable code, and test an edge case.

PYTHON LESSON PREVIEW
Mistakes lessonLearn → test

Core idea

One omitted boundary can invalidate a correct-looking algorithm.

Wrong loop → missed item
Minimal test → cause
Repair → regression
Check the output and reasoning.Compare the result with expected outputs and edge cases.

The direct answer

Catch the edge case that the sample never showed.

Interview solutions often fail on a boundary rather than the central idea: a binary search skips the final position, a mutable default retains data, or an empty input violates an unstated assumption. The repair is to define the contract and keep a minimal regression test.

This lesson compares a deliberately wrong binary search with the tested version from the 20-problem module. It also catalogues common failures and their smallest useful fixtures. The course pricing block follows this introduction.

Course access

Choose your next step in Python.

Review the current course options and access details here.

Heycademy Courses · Coming Soon

Master Python with Heycademy

We’re preparing an interactive learning experience with practical exercises, skill assessments and personalized learning to help you build confidence and master new skills.

Launching soon!
We’re putting the finishing touches on this course. Please check back for updates.

Failure catalog

Test the condition the loop barely touches.

Original Python failure fixtures
MistakeSmall fixtureFailureCorrection
Off-by-one search[1,3,5], target 5Last index never checked.Inclusive loop uses left <= right.
Mutable defaultCall append helper twice.Second call sees first call state.Use None sentinel.
Empty inputMaximum subarray of [].No initial best value.Document error or sentinel.
Wrong duplicate handlingTwo-sum [3,3], target 6.Same index reused or pair missed.Check complement before insert.
Iterator reuseConsume iterator, then list again.Second pass empty.Recreate/materialize deliberately.
Shallow nested copyCopy outer grid, mutate inner.Both grids change.Define deep-copy need.

A test suite should include at least one normal case, one boundary case and one case that challenges the chosen invariant. “Edge case” is not a synonym for random unusual data; it is a targeted probe of a decision the code makes.

Wrong binary search

The last candidate remains unexamined.

def binary_search_wrong(values, target):
    left, right = 0, len(values) - 1
    while left < right:
        middle = (left + right) // 2
        if values[middle] == target:
            return middle
        if values[middle] < target:
            left = middle + 1
        else:
            right = middle - 1
    return -1

For [1,3,5] and target 5, the loop eventually narrows to left == right == 2. The condition left < right stops before checking index 2 and returns -1. The same mistake appears with a one-element list whose sole value is the target.

Failing search fixtures
InputExpectedWrong codeCause
[1,3,5], target 52-1Final candidate skipped.
[5], target 50-1Loop never runs.
[], target 5-1-1No candidate; result happens to be right.

One passing empty test cannot prove the loop is correct. Test positions at the start, middle and end, plus an absent target.

Correct inclusive bounds

Check while a candidate still exists.

def binary_search(values, target):
    left, right = 0, len(values) - 1
    while left <= right:
        middle = (left + right) // 2
        if values[middle] == target:
            return middle
        if values[middle] < target:
            left = middle + 1
        else:
            right = middle - 1
    return -1

The invariant is that if the target exists, it lies within the inclusive interval [left, right]. Therefore the loop continues while left <= right. Each comparison removes the middle or one side. When left > right, no candidate remains. The input must be sorted under the same comparison used by the code.

assert binary_search([1, 3, 5], 5) == 2
assert binary_search([5], 5) == 0
assert binary_search([], 5) == -1

These checks were run in the accompanying test module. If duplicate values exist, the function returns a matching index but does not promise the first one; use a lower-bound contract if the first position is required.

Keep building this skill

Turn the example into a tested solution.

Return to the course options whenever you are ready.

Explore course options →

Mutable defaults and empty inputs

Specify the policy before the fix.

A mutable default list persists across calls because Python evaluates the default once at definition time. The Python FAQ recommends a None sentinel when each omitted call needs a fresh object. The debugging lesson shows a tested-style repair and an explicit-empty-list check.

An empty input requires a deliberate contract. In the tested max_subarray_sum, an empty list raises ValueError because “nonempty contiguous subarray” has no answer. In the tested contains_duplicate, an empty list sensibly returns False. Do not force one universal empty-input rule across unrelated problems.

Repeatable review method

Write a counterexample before changing code.

  1. State the intended invariant and boundary convention.
  2. Find the smallest input that violates it.
  3. Predict actual execution line by line.
  4. Fix the root cause without silently changing the output contract.
  5. Keep the failing input as a regression test and add a nearby case.

For binary search, draw the interval after each iteration. For aliasing, inspect identity as well as value. For a default argument, call twice. For an iterator, consume it once and check the second pass. These targeted probes are efficient because each tests one assumption.

New binary-search case

What about a duplicate target?

Given [1,2,2,2,4] and target 2, the basic binary search may return any index holding 2. If the new requirement is “first index at least 2,” use the lower-bound solution instead. Its half-open interval has a different invariant.

What is the first position at least 3?

Index 4, because values at indices 0–3 are below 3 or equal 2, and value 4 is at index 4.

The change from “find a matching index” to “find first eligible index” is a contract change. It should trigger an algorithm and test review, not only a one-character patch.

Build a compact boundary suite

Each input should challenge a different claim.

Binary search boundary suite
ClaimSmall testWhat failure reveals
Loop checks final candidate.[1,3,5], target 5.Wrong loop condition.
Singleton works.[5], target 5.Loop may never execute.
Absence is handled.[1,3,5], target 4.Wrong termination/result.
Duplicates have stated meaning.[1,2,2,4], target 2.Any-match versus first-match confusion.
Empty input is safe.[], target 5.Invalid index access.

Five tiny cases are more diagnostic than a single long random list. They isolate a boundary, result policy or invariant. Once the function passes, keep the suite as a regression check. Add a test for a changed contract only after stating that contract; otherwise you may “fix” code that was correctly solving a different task.

A reusable failure note

Record the cause, not merely the passing test.

For the wrong binary search, record: input [1,3,5], target 5; expected index 2; actual -1; cause: inclusive final candidate skipped when left equals right; repair: continue while left is at most right; regression: same case plus singleton [5]. That note is specific enough to guide a later review without rereading the whole solution.

The unittest documentation shows how to keep such fixtures executable. A test protects the repair only if it would fail when the bug returns. Testing [1,3,5] for target 3 alone would not catch the omitted-final-candidate bug because the middle value may be found before the loop reaches the boundary.

FAQ

Questions about this skill.

Why does left < right fail here?

The inclusive interval can contain one final candidate when left equals right.

Should binary search accept unsorted data?

No. This implementation requires ascending sorted input.

What should an empty maximum-subarray input do?

The tested course contract raises ValueError; another contract must be stated explicitly.

Continue with the course

Build reliable Python interview skills.

Review the course options and choose your next learning step.

Take the next step →
Scroll to Top