Codzy

Data structures: stacks, queues and heaps

A stack works like a pile of plates: the last item added is the first one removed (LIFO). A plain list is enough, with append() and pop().

A queue works like a waiting line: first come, first served (FIFO). Use collections.deque, with append() and popleft(), which is fast at both ends. A heap (the heapq module) always gives the smallest item first, ideal for handling priorities.

from collections import deque
import heapq

stack = []
stack.append("a")
stack.append("b")
print(stack.pop())

queue = deque(["first", "second"])
queue.append("third")
print(queue.popleft())

tasks = [5, 1, 3]
heapq.heapify(tasks)
print(heapq.heappop(tasks))

Start the lesson