The cost of Python operations

Most slow interview code comes from a few operations. Learn this table.

Operation Cost
lst[i], lst.append(x), lst.pop() O(1)
x in lst, lst.index(x), lst.remove(x) O(n)
lst.insert(0, x), lst.pop(0) O(n)
lst[a:b], lst.copy() O(b - a), O(n)
d[k], k in d, d[k] = v O(1) on average
x in s, s.add(x) O(1) on average
deque.append, deque.popleft O(1)
sorted(lst), lst.sort() O(n log n)
s += t in a loop can be O(n²) overall
"".join(parts) O(total length)

What to remember: lists are fast at the end and slow at the front. Use a deque for a queue. Use a set or dict when you check membership in a loop. Build strings in a list and join once.

Run it to see pop(0) against popleft(). Then raise n and watch the gap grow.