Why is appending to a Python list constant time while inserting at position zero is linear, and what code shows the difference?
Because a Python list is a contiguous block of memory with a pointer to each element. Appending writes into the free space at the end and bumps a length counter, which is a fixed amount of work. Inserting at the front has no free space at the front, so every existing element must shift one slot to the right to make room. That is n moves, so the operation is O(n).
from collections import deque
stack = [1, 2, 3, 4, 5]
stack.insert(0, 0)
print(stack)
queue = deque([1, 2, 3, 4, 5])
queue.appendleft(0)
print(list(queue))Both lines print the same sequence, zero followed by one through five, but the work behind them is completely different. The list version physically relocated five elements. The deque version stores elements in small blocks with links between them and keeps an index of where the front begins, so adding to the front is a matter of writing one cell and moving that index along.
The trade-off to state is that a list gives you cheap random access, since element i sits at a computable offset, while a deque gives you cheap insertion and removal at both ends. Pick the container for the operation you perform most often. If a workload appends and pops from the front in a loop, using a list costs quadratic time across the run, and switching to a deque turns that into linear.
Two practical notes round this off. The deque indexing by position is O(n), so if you need random access, convert to a list first. And the shift cost of insert is not always paid: Python lists keep a small amount of spare capacity, so appending amortised over many operations is constant, even though any single append can occasionally trigger a full reallocation and copy.