In place or a new list: what the interviewer means

Two pointers Junior Python 3.13+ Reviewed By Best Latest Apps

Predict the output

What does this print?

Python 3.13
def a(xs: list[int]) -> None:
    xs = [0] * len(xs)

def b(xs: list[int]) -> None:
    xs[:] = [0] * len(xs)

u, v = [1, 2], [1, 2]
a(u)
b(v)
print(u, v)

Options

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A [1, 2] [0, 0]

Right: a rebinds its local name; b writes into the caller's list.

Both functions build the same new list; only the way it is stored differs, which is why the callers see different results.

Why not the others?
  • B [0, 0] [0, 0]. a never touches the caller's list; it only rebinds xs.
  • C [1, 2] [1, 2]. Slice assignment in b changes the original list.

30-second answer

In place means O(1) extra working memory: you rearrange the given list instead of building another one, and the caller sees the change. In Python, reassigning the parameter name only rebinds a local variable; mutate with index assignment, slice assignment or methods. The output list itself does not count as extra space when one is required.

Practise saying it · 30 s. No recording, just a timer

Explain what 'in place' means in Python.

Say your answer out loud, then check which of these points you covered:

  • O(1) extra memory
  • Mutate, do not rebind
  • Slice assignment

Deep dive

nums[:] = new_values replaces the contents of the caller's list; nums = new_values does not.

Recursion uses stack space; a recursive 'in place' sort still uses O(log n) or more stack.

Interviewers accept a copy-based answer first if you say its cost and then improve it.

Common mistakes

  • Returning a new list and assuming the caller's list changed.
  • Calling sorted() instead of .sort() when the question wants the original list sorted.

Senior take & follow-ups

Show you know the aliasing rule with one sentence; it prevents the most common silent bug in Python answers.

Follow-up questions

Think of your answer first, then open the hint.

  1. Is slicing in place?

    Show hint

    Reading a slice copies; assigning to a slice mutates the original list.

  2. Does in place mean O(1) time?

    Show hint

    No, it is about memory; the work is usually still O(n).

What each operation costs: Arrays · Array Operations

From the author

DSA Master - Data & Algorithms

Free on iPhone and iPad: watch 50+ data structures and algorithms step through animations, run the code in the playground, and try the daily challenge.

Suggest a fix if something here is wrong or out of date.