Skip to content
KALANBLON
Show contents

Chapter 1 of 7 · 20 min

Stacks and queues

By the end of this chapter, you'll be able to

  • Tell a stack (last in, first out) from a queue (first in, first out)
  • Use a Python list as a stack with append and pop
  • Use collections.deque as a queue with append and popleft
  • Choose the right structure for the processing order you need

The stack: last in, first out

A data structure is a way of organising values in memory so you can find and change them efficiently. A stack works like a pile of plates: you put a plate on top, and you always take back the one on top. It follows the LIFO rule: last in, first out.

In Python, a plain list makes an excellent stack:

  • append(x) puts x on top;
  • pop() removes and returns the top item;
  • stack[-1] looks at the top without removing it.

Here is the "undo" history of a word processor:

history = []
for action in ["type “Hello”", "make bold", "change colour"]:
    history.append(action)
    print("done:", action)

print("undo:", history.pop())
print("undo:", history.pop())
print("left:", history)
done: type “Hello”
done: make bold
done: change colour
undo: change colour
undo: make bold
left: ['type “Hello”']

append and pop() with no argument work at the end of the list: Python has nothing to shift, so these operations take constant time, written O(1), whatever the size of the stack.

A, the first one in, will come out last.

Step 7 of 7
Text description of the animation
  1. We start from an empty stack.
  2. The empty list will be our stack.
  3. append puts A on top.
  4. B goes on top of A.
  5. C is now on top.
  6. pop removes the last one in: C.
  7. A, the first one in, will come out last.

The queue: first in, first out

A queue works like a waiting line: you join at the back, you are served at the front. It follows the FIFO rule: first in, first out.

For a queue, Python offers collections.deque (pronounced "deck"): you add on the right with append and remove on the left with popleft, both in O(1).

from collections import deque

counter = deque()
for customer in ["Awa", "Kofi", "Lina"]:
    counter.append(customer)
    print(customer, "takes a ticket")

print("at the counter:", counter.popleft())
counter.append("Tariq")
print("at the counter:", counter.popleft())
print("waiting:", list(counter))
Awa takes a ticket
Kofi takes a ticket
Lina takes a ticket
at the counter: Awa
at the counter: Kofi
waiting: ['Lina', 'Tariq']

Awa, who arrived first, is served first. Tariq, who arrived after everyone, will go last: nobody jumps the queue.

NeedStructureAddRemove
Undo, go backstack (list)appendpop()
Serve in order of arrivalqueue (deque)appendpopleft()

Mini-lab: stack or queue?Python 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: balanced brackets

A code editor wants to check that an expression is properly bracketed: every (, [ or { must be closed by the matching symbol, in the right order. Write balanced(text) that returns True or False.

print(balanced("(2 + 3) * [4 - 1]"))   # True
print(balanced("{[()]}"))              # True
print(balanced("(]"))                  # False
print(balanced("(()"))                 # False
Hint 1
The last symbol opened is the first one that must be closed: that is exactly the rule of a stack.
Hint 2
Push every opening symbol. On each closing symbol, the stack must not be empty and its top must be the matching opener. At the end, the stack must be empty.
Show the solution and common mistakes
def balanced(text):
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for c in text:
        if c in "([{":
            stack.append(c)
        elif c in pairs:
            if not stack or stack.pop() != pairs[c]:
                return False
    return not stack

print(balanced("(2 + 3) * [4 - 1]"))
print(balanced("{[()]}"))
print(balanced("(]"))
print(balanced("(()"))
True
True
False
False

Common mistakes:

  • Only counting openers and closers: "(]" has as many of each, yet it is wrong. Order matters, hence the stack.
  • Forgetting the empty-stack case: with ")", stack.pop() would raise an IndexError. The not stack test comes first.
  • Returning True at the end without checking that the stack is empty: "(()" would leave an unclosed opener behind.

Summary

  1. 1A stack follows the rule “last in, first out”; a Python list with append and pop() makes a very good one.
  2. 2A queue follows the rule “first in, first out”; collections.deque with append and popleft() is built for it.
  3. 3Undo, go back, check brackets: stack. Serve in order of arrival: queue.
  4. 4list.pop(0) shifts every item: to remove from the front, use a deque.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.