Skip to content
Performance

Why is list.pop(0) slow in Python?

Why is list.pop(0) slow in Python? A list is a contiguous array, so removing the first item shifts every other item left, costing O(n) per call. Here is the arithmetic, the fix with deque, and when it truly does not matter.

Why is list.pop(0) slow in Python? A list is one contiguous block of pointers, so removing the first element forces every remaining pointer to shift one slot left. That is O(n) work for each call. Use collections.deque and popleft() instead, which removes from the front in O(1).

That answer is correct, but it hides the part that decides whether you should care. A single pop(0) on a short list is invisible. The same call inside a loop that drains a large queue is the difference between a solution that finishes in milliseconds and one that gets killed by the time limit. This essay walks through what the interpreter does, puts real numbers on it, and lists the replacements in order of how often I reach for them.

What does list.pop(0) actually do inside CPython?

It removes the first slot of a dynamic array and then moves the entire rest of the array one position toward the front. CPython stores a list as a header plus a single heap-allocated array of pointers, each 8 bytes on a 64-bit build. Slot 0 is the start of that array, and there is no spare room before it, so there is nowhere to "advance" a start marker to.

Here is the mental model I use. Picture a bookshelf where no gaps are allowed and the leftmost book must always sit at the left edge. Taking out the first book is easy. Then you have to slide every other book one slot to the left, because the rule says the shelf starts at the edge. A shelf of 10 books costs you 9 slides. A shelf of 100,000 books costs you 99,999 slides, for every single removal. The fix, as we will see, is to stop insisting on the rule: keep a bookmark for where the shelf currently starts, or use a shelf built from several smaller shelves chained together.

Internally the shift is a memmove over the tail of the array, not a Python-level loop. That matters, because it is fast per element. But fast per element times n elements times n calls is still quadratic. The complexity class does not care that the constant is small; it only delays the point where you notice.

The same story applies to list.insert(0, x), to del a[0], and to the innocent-looking a = a[1:], which allocates a brand new list and copies n-1 pointers. All four are O(n). If you see any of them inside a loop over the same list, you have an accidental quadratic.

How slow is it on a real queue, in numbers?

For a list holding 100,000 items that you drain completely with pop(0), the interpreter moves about 5 billion pointers, which is roughly 40 GB of memory traffic and a couple of seconds of wall time. The same drain with a deque moves nothing and takes a few milliseconds.

Let me do the arithmetic properly, because the shape of the sum is the point. You start with n = 100,000 items. The first pop(0) shifts 99,999 pointers. The second shifts 99,998. The last shifts 0. The total is n(n-1)/2, which for this n is 4,999,950,000, call it 5 × 109 pointer moves. At 8 bytes each that is 40 × 109 bytes. A modern core can push memmove at somewhere between 10 and 20 GB/s when the data sits in cache, and an 800 KB array fits comfortably in L2 or L3, so you land at 2 to 4 seconds. Treat those as order-of-magnitude figures and measure on your own machine, but the conclusion does not depend on the exact bandwidth.

Now the deque version. Each popleft() reads one slot and bumps an index. At around 30 to 60 nanoseconds per call in CPython, 100,000 calls cost 3 to 6 milliseconds. That is roughly a 500x gap at this size, and the gap grows linearly with n. At n = 1,000,000 the list version would not take 10 times longer; it would take about 100 times longer, in the region of several minutes, because the total work is quadratic.

A caution before you conclude that every BFS in Python is broken. Real breadth-first search rarely holds all n items in the queue at once. On a 1000 by 1000 grid (106 cells), the frontier is at most a couple of thousand cells wide. Each pop(0) then shifts about 2,000 pointers, which is 16 KB and on the order of a microsecond. Across 106 pops you pay around a second extra. That is survivable on a lenient limit and fatal on a strict one. So the real cost of pop(0) in a BFS is the frontier size times the number of pops, not n squared, and it is exactly why the bug appears "randomly" on some inputs (a wide, bushy graph) and not on others (a long thin path).

from collections import deque

# Quadratic on a large frontier
queue = [start]
while queue:
    node = queue.pop(0)          # O(len(queue)) every time
    for nxt in neighbours(node):
        queue.append(nxt)

# Linear in total pushes
queue = deque([start])
while queue:
    node = queue.popleft()       # O(1)
    for nxt in neighbours(node):
        queue.append(nxt)

If you want to see this pattern in a problem that punishes the slow version, Number of Islands solved with BFS on a large grid is a good place to measure it yourself.

Why is pop() from the end fast when pop(0) is slow?

Because removing the last element touches no other element. The array simply forgets its final slot by decrementing the length, which is O(1), and occasionally shrinks its allocation, which is cheap on average.

This asymmetry is the whole reason Python lists make good stacks and bad queues. Appending at the end is amortized O(1): most appends write into spare capacity, and the occasional resize copies everything but is paid for by the many cheap appends before it (the amortized analysis is worth knowing cold). Popping from the end is the mirror image. Both operations work on the end where free space lives. The front has no free space, and the data structure has no way to create any without moving things.

It is worth noticing that this is a property of the layout, not of the language being slow. The same decision, a flat contiguous array, is what makes indexing a[i] a single address computation and iteration cache-friendly. You are trading cheap front removal for cheap random access. I wrote about why that trade usually wins in why arrays beat linked lists in practice; pop(0) is the one place where the bill arrives.

What should you use instead of list.pop(0)?

Use collections.deque with popleft() when you need a real queue. When you only need to read items in order and never reuse the consumed ones, a plain list with a moving head index is just as fast and sometimes simpler.

Here are the options side by side, with the cost of removing the front element and the catch for each.

ApproachRemove frontAppend backIndex a[i]Catch
list.pop(0)O(n)O(1) amortizedO(1)Quadratic when drained in a loop
a = a[1:]O(n), allocatesO(1) amortizedO(1)Copies the whole list every time, worst of both
deque.popleft()O(1)O(1)O(n) in the middleSlow random access, slightly more memory per item
list + head indexO(1)O(1) amortizedO(1) from headConsumed items stay in memory until you clear them
reversed list + pop()O(1)O(n) at the frontO(1)Only works when you fill once, then drain

My ordering of preference is deque first, head index second, reversed list third. The deque is the default because it says what you mean: the reader sees a queue and does not have to verify an index invariant. The head index wins when the queue is a flat batch of work, for example processing a precomputed list of tasks, because you keep random access and avoid the import. The reversed list is a neat trick for one fill followed by one drain, such as reading tokens, but it is fragile once someone adds a push to the wrong end.

# Head index version: no shifting, items stay in place
items = list(range(100000))
head = 0
while head < len(items):
    x = items[head]
    head += 1
    if x % 7 == 0:
        items.append(x + 1)   # new work goes to the back

The head-index loop keeps every consumed item alive. For a million items that is 8 MB of pointers plus the objects themselves, which is usually fine. If it is not, set items[head - 1] = None after reading, or compact the list once head passes half the length. Compaction costs O(n) but runs only after n/2 pops, so it adds O(1) amortized per pop, the same argument as list growth.

Does deque have a catch?

Yes: indexing into the middle of a deque is O(n), so it is a queue and not a faster list. If you need to read d[len(d) // 2] repeatedly, a deque will punish you.

CPython implements deque as a doubly linked list of fixed-size blocks, each holding 64 pointers. popleft() moves an index inside the leftmost block and frees that block when it empties. Appending does the mirror at the right end. Both are O(1) because they never move items between blocks. Random access, however, has to walk the chain from whichever end is closer. For a deque of 1,000,000 items, reaching the middle means hopping across roughly 7,800 blocks. That is far better than a pure linked list of 500,000 nodes, but it is nowhere near O(1).

So the question to ask is what operations you perform, not which structure is fastest in the abstract. A sliding window maximum needs both ends and no middle access: deque is perfect. Binary searching over a queue's contents needs the middle: use a list and a head index. Choose by the access pattern, and the right container usually becomes obvious.

Is this only a Python problem?

No. Any language whose default growable array is a flat contiguous buffer has the same cost for removing the first element. Java's ArrayList.remove(0), C++ std::vector::erase(begin()), and Go slice deletion by copy all shift the tail, and each language ships a dedicated queue type (ArrayDeque, std::deque, a ring buffer) for the reason Python does.

Some runtimes soften the blow. JavaScript engines have been known to apply tricks to Array.prototype.shift on certain array shapes and sizes, so a shift loop can look fine in one benchmark and collapse in another. I would not build on an optimisation the specification does not promise. The portable habit is the one worth learning: if the first element is leaving, ask whether the container is designed for that.

This is also why the idea of a ring buffer is worth carrying around. A fixed array with a head index and a tail index, wrapping with modulo, gives O(1) at both ends and O(1) random access, at the cost of a capacity limit or an occasional resize. Deque trades that for unbounded growth and block-by-block allocation. Same goal, different engineering.

When is list.pop(0) perfectly fine?

When the list is small and bounded, or when the call happens a handful of times rather than once per element. A list of 20 items popped from the front 20 times costs about 200 pointer moves, which is less than the overhead of importing deque.

I do not think the right lesson is "never write pop(0)". The right lesson is to attach a size to it. Ask what the largest the list can get, and how many times the call runs. If the product of those two numbers is under a few hundred thousand, nobody will ever see the cost. If the list is bounded by an input you do not control, a query count or a graph size, treat the call as O(n) in that input and write the deque version from the start. It costs one import and changes nothing else in the loop.

In interviews this has a specific shape. Writing pop(0) in a BFS is not a failure on its own, but an interviewer who asks "what is the complexity of your BFS?" expects O(V + E), and that answer is only true with an O(1) dequeue. Say so out loud, name deque, and you have shown that you know the difference between the algorithm's complexity and the container's. The complexity of an algorithm is always conditional on the operations of the structures underneath it, a point I make at more length in Complexity is a contract, not a fact.

Frequently asked questions

Is list.pop() also slow?

No. Calling pop() with no argument removes the last element, which is O(1) because no other element has to move. Only popping from the front or the middle triggers a shift, and the cost is proportional to how many elements sit after the removed index.

Is deque always faster than a list for queues?

For removing from the front, yes, by a wide margin once the queue holds more than a few hundred items. For tiny queues the difference is negligible, and for random access in the middle a list is faster. Pick deque when both ends matter and the middle does not.

Why not just use a linked list for a queue in Python?

A hand-written linked list allocates one Python object per node, which costs far more memory and time per operation than deque's 64-pointer blocks. Deque gives you the O(1) end operations of a linked list with much better cache behaviour, so there is rarely a reason to build your own.

The quickest way to feel this in your hands is to take a BFS you have already written and time it both ways on a wide input. Start with the BFS versus DFS decision guide, rewrite the queue with deque, and compare the two runs.