7/32
Part 2 of 7 · Breadth-first searchLearn and do

Use a deque, because a list's pop(0) shifts every item behind it

The search takes cells from the front of its queue. A list is the wrong tool for that.

Taking the first item out
list.pop(0)
abcde
deque.popleft()
abcde

Red leaves. In the list, the 4 orange items behind it each move one place. In the deque, nothing else moves.

A Python list keeps its items side by side, so taking the first one shifts every other item down one place. The Python tutorial says so: pops from the front of a list are slow. collections.deque, a double-ended queue, is built for both ends, with about the same O(1) cost for an append or a pop on either side.

Drain one of each:

import time
from collections import deque

n = 200_000
as_list, as_deque = list(range(n)), deque(range(n))

start = time.perf_counter()
while as_list:
    as_list.pop(0)
print(f"list.pop(0):     {time.perf_counter() - start:.2f} s")

start = time.perf_counter()
while as_deque:
    as_deque.popleft()
print(f"deque.popleft(): {time.perf_counter() - start:.4f} s")
Predict

Draining 200,000 items with list.pop(0) took about 3.2 s. About how long for 100,000?

Pick an answer above to see the rest