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, whateverxis (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 positioni.- All three mutate the list in place and return
None, soa = a.append(x)destroys the list. insertclamps out-of-range positions and accepts negative ones;a += iterableisextend(in place, any iterable) whilea + bbuilds a new list and requires a list.- Costs:
appendis amortised O(1) thanks to over-allocation,extendis O(k),insert(0, x)is O(n) because every item shifts β usecollections.dequefor 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.