Python Lists · Lesson 46 of 149

Python Lists as Stacks and Queues

What you will learn

  • What a stack is (LIFO) and how to use a list as one
  • What a queue is (FIFO), and why pop(0) on a list is slow
  • collections.deque: fast at both ends
  • A deque with a maximum length, and rotate
  • Real uses: undo, matching brackets, breadth-first search

1. Stack: last in, first out

A stack works like a pile of plates: you put a plate on top, and you take the plate from the top. The last item added is the first to come off, which is why it is called LIFO (last in, first out).

A list is a good stack. append pushes onto the top, and pop() takes off the top (lesson 7.2):

stack = []
stack.append("a")
stack.append("b")
stack.append("c")
print(stack)
print(stack[-1])
print(stack.pop())
print(stack.pop())
print(stack)
['a', 'b', 'c']
c
c
b
['a']
  • stack[-1] looks at the top without removing it (often called peek).
  • stack.pop() removes and returns the top.
  • if stack: is true while the stack is not empty (lesson 7.1).

Popping from an empty list is an error:

stack.pop()
stack.pop()
IndexError: pop from empty list

(The first pop() removes the last item a, and the second one fails.) Check with if stack: before popping when the stack might be empty.

Quick check: after pushing `1`, `2`, `3` in that order, which item does `pop()` return?

3, the last one pushed.

2. Where stacks are used

Undo. Every action is pushed onto a history; undo pops the latest one:

history = []
for action in ["type A", "type B", "type C"]:
    history.append(action)

undone = history.pop()
print("undid:", undone, "| left:", history)
undid: type C | left: ['type A', 'type B']

Matching brackets. Push every opening bracket; when a closing bracket appears, it must match the one on top:

def balanced(text):
    pairs = {")": "(", "]": "[", "}": "{"}
    st = []
    for ch in text:
        if ch in "([{":
            st.append(ch)
        elif ch in pairs:
            if not st or st.pop() != pairs[ch]:
                return False
    return not st

print([balanced(s) for s in ["(a[b]{c})", "(]", "((", "", ")("]])
[True, False, False, True, False]
Text Balanced? Why
(a[b]{c}) yes every opener is closed in the right order
(] no ] does not match the ( on top
(( no openers are left over
`` (empty) yes nothing to match
)( no a closer arrives with nothing to match

Your computer uses a stack too, to remember where to return when functions call other functions (chapter 11).

3. Queue: first in, first out

A queue works like a line at a shop: people join at the back and are served from the front. The first to arrive is the first to be served: FIFO (first in, first out).

You can do this with a list, using append to join and pop(0) to serve:

q = []
q.append("Rina")
q.append("Sam")
q.append("Lee")
served = q.pop(0)
print(served, q)
Rina ['Sam', 'Lee']

It works, but there is a hidden cost. A list is stored as a row of slots, and pop(0) removes the first slot, so every other item must move one place to fill the gap. For a long list, each pop(0) gets slower. (insert(0, x) has the same problem.) Taking from the end (pop()) is quick, because nothing has to move.

4. deque: fast at both ends

For queues, use collections.deque (say "deck", short for double-ended queue). Adding and removing at either end is fast:

from collections import deque

dq = deque()
dq.append(1)
dq.append(2)
dq.appendleft(0)
print(dq)
print(dq.popleft(), dq.pop())
print(dq)
deque([0, 1, 2])
0 2
deque([1])
Method Meaning
append(x) / appendleft(x) add at the right end / the left end
pop() / popleft() remove and return from the right / the left
rotate(n) move the items n places to the right (negative: left)
extend(items) / extendleft(items) add many at one end

You can still use len, in, loops and [0] or [-1]. Indexing into the middle of a very long deque is slow, so a deque is for both ends, not for random access. And popleft() on an empty deque is an IndexError: pop from an empty deque.

A quick test showed pop(0) on a long list taking longer than popleft() on a deque. Exact speeds vary from computer to computer; to measure your own code, use timeit (lesson 18.5).

A queue in action

tasks = deque(["t1", "t2", "t3"])
order = []
while tasks:
    order.append(tasks.popleft())
print(order)
['t1', 't2', 't3']

The tasks leave in the order they arrived.

5. A deque with a maximum length

Give maxlen and the deque drops items from the other end when it gets full. It is perfect for "the last n items":

last3 = deque(maxlen=3)
for v in range(10):
    last3.append(v)
print(list(last3))
[7, 8, 9]

Only the three most recent values are kept. This is handy for a moving window, recent history or a log tail.

6. rotate

rotate(n) turns the deque like a wheel, moving items from one end to the other:

r = deque([1, 2, 3, 4, 5])
r.rotate(2)
print(r)
r.rotate(-2)
print(r)
deque([4, 5, 1, 2, 3])
deque([1, 2, 3, 4, 5])

A classic use is breadth-first search: visit places level by level, using a queue of places still to visit. This example finds the order in which a small map (made-up) is explored from A:

graph = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []}
seen = ["A"]
todo = deque(["A"])
while todo:
    node = todo.popleft()
    for nxt in graph[node]:
        if nxt not in seen:
            seen.append(nxt)
            todo.append(nxt)
print(seen)
['A', 'B', 'C', 'D']

todo holds the places waiting to be visited. Taking from the front means older discoveries are handled first, so nearer places come before farther ones. Using a stack (pop()) instead gives depth-first search, which dives deep before it returns.

8. Other queues

Tool Use
collections.deque the general-purpose queue and stack
heapq a priority queue: always gives the smallest item first
queue.Queue, queue.LifoQueue queues for threads that need locking (lesson 20.2)
import heapq

h = []
for v in [5, 1, 3]:
    heapq.heappush(h, v)
print(heapq.heappop(h), h[0])
1 3

heappop always returns the smallest item, whatever order they arrived in.

Worked example: recent searches

A search box remembers the last three searches. The newest should show first.

from collections import deque

recent = deque(maxlen=3)
for term in ["python", "loops", "lists", "tuples"]:
    recent.appendleft(term)
print(list(recent))
['tuples', 'lists', 'loops']
Step State
python python
loops loops, python
lists lists, loops, python
tuples tuples, lists, loops (python fell off the end)

appendleft puts the newest at the front, and maxlen=3 removes the oldest from the other end by itself. The search terms are made up.

Common mistakes

  • Using pop(0) or insert(0, x) on a long list as a queue. Use a deque.
  • Calling pop() on an empty stack or queue without checking.
  • Mixing up the ends: a stack takes from the same end it adds to; a queue takes from the other.
  • Expecting fast indexing in the middle of a deque.
  • Forgetting that a full maxlen deque drops items silently.

Key takeaways

  • A stack is last-in-first-out: append to push, pop() to pop, stack[-1] to peek; a list is ideal.
  • A queue is first-in-first-out; a list is slow for it because pop(0) shifts every item.
  • collections.deque has fast append, appendleft, pop and popleft, and rotate.
  • deque(maxlen=n) keeps only the last n items.
  • Stacks suit undo and bracket matching; queues suit waiting lines and breadth-first search; heapq gives a priority queue.

Practice

1. What does popleft() return for deque([7, 8, 9]), and what is left?

Show answer

7, and the deque is deque([8, 9]).

2. Why is q.pop(0) slow on a list with a million items?

Show answer

Removing the first item makes every other item move one place to fill the gap, so each call takes longer the longer the list is.

3. What is the output after pushing "x", "y", then popping once, on a list used as a stack?

Show answer

The list is ['x'], and the popped value was "y".

4. Keep only the last 5 values read from a stream. Which tool and which setting?

Show answer

deque(maxlen=5): appending a sixth value drops the oldest one.

5. Is ")(" balanced, and why?

Show answer

No. The closing bracket comes first, when the stack is empty, so there is nothing to match it.

6. Which structure always returns the smallest item first?

Show answer

A heap, from the heapq module (heappush and heappop).