Skip to the solution
EasyBackend13 min read

What is the difference between append, extend and insert on a list?

1.1k views

The problem

Question presented to candidate: "What is the difference between append, extend and insert on a Python list? If I call a.append([3, 4]) and a.extend([3, 4]), what does a look like in each case, and which of these is slow on a big list?"

What a strong answer should cover:

  • append(x) adds exactly one item at the end, whatever x is (a list becomes one nested element); extend(iterable) adds each item of any iterable (a string adds its characters); insert(i, x) puts one item before position i.
  • All three mutate the list in place and return None, so a = a.append(x) destroys the list.
  • insert clamps out-of-range positions and accepts negative ones; a += iterable is extend (in place, any iterable) while a + b builds a new list and requires a list.
  • Costs: append is amortised O(1) thanks to over-allocation, extend is O(k), insert(0, x) is O(n) because every item shifts β€” use collections.deque for frequent front inserts.
  • A CPython detail: a list is an array of pointers, so appending a big object copies one pointer, not the object.

Code / implementation expected: Optional β€” a few lines showing the append versus extend result is the usual check.

  • lists
  • basics

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read Β· 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

Pythonappend vs extend vs insert, += vs +, and the tuple += gotcha
PythonMeasuring over-allocation and the cost of front inserts

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 7 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextEasy

How does iterable unpacking work?

Continue