Skip to content

Stacks & Queues

1 min read2 lessons in topic

Learning objective

By the end of this lesson you will be able to explain LIFO stacks and FIFO queues and use them in Python.

Stacks and queues are simple structures with strict rules about order — and they appear everywhere in real software.

Stack — last in, first out (LIFO)

Think of a stack of plates: you take the top plate first. The last item pushed is the first item popped.

stack = []
stack.append("open tab 1")
stack.append("open tab 2")
print(stack.pop())   # open tab 2
print(stack.pop())   # open tab 1

Queue — first in, first out (FIFO)

Like a queue at a counter: the first person in is served first.

from collections import deque
queue = deque(["Ama", "Kofi", "Esi"])
print(queue.popleft())  # Ama served
print(queue.popleft())  # Kofi served

Where they appear

  • Browser back button — a stack of pages
  • Undo / redo — a stack of actions
  • Print jobs — a queue
  • Task scheduling — a queue

Code playground

Run and edit the starter code — experiment freely.

python · runnable

Output appears here when you press Run.

Practice exercise

Simulate a browser back button with a stack: push three pages, then pop twice and print the current page.

Check your understanding

1. A stack removes items in which order?

2. Which data structure fits a print queue best?

Self-graded — answer then check below.