Python · Heaps · Stacks · Queues

Complete Guide to Heaps, Stacks & Queues in Python

In this chapter you will learn three fundamental data structures: Stacks (LIFO), Queues (FIFO) and Heaps (priority queues), with diagrams, time complexity and Python implementations.

STACK · LIFO

1. Stacks (LIFO)

A stack is a linear data structure that follows the LIFO (Last In, First Out) principle. The last element added is the first one removed – like a stack of plates.

1.1 What is a Stack?

A stack is a linear data structure that follows the LIFO (Last In, First Out) principle. The last element added is the first one removed – like a stack of plates.

Top → [ 30 ] ← removed first (pop) [ 20 ] Bottom [ 10 ]

1.2 Core Stack Operations

OperationDescriptionTime
push(x)Insert item onto the top of the stackO(1)
pop()Remove and return top itemO(1)
peek()Return top item without removing itO(1)
is_empty()Check if stack has no elementsO(1)

1.3 Stack Using Python List

Python's built-in list can be used as a stack with append() and pop() methods.

1.4 Custom Stack Class

Here is a simple implementation of a Stack class in Python:

1.5 Real-World Uses of Stacks

Stacks are widely used in various applications, such as:

QUEUE · FIFO

2. Queues (FIFO)

A queue is a linear data structure that follows FIFO (First In, First Out). The first element added is the first one removed – like a line of people waiting for tickets.

2.1 What is a Queue?

A queue is a linear data structure that follows FIFO (First In, First Out). The first element added is the first one removed – like a line of people waiting for tickets.

Front → [ 10 ] → [ 20 ] → [ 30 ] → Back dequeued first

2.2 Core Queue Operations

The main operations for a queue are:

OperationDescriptionTime
enqueue(x)Insert item at the back of the queueO(1)
dequeue()Remove and return front itemO(1) with deque
peek()View the front item without removing itO(1)
is_empty()Check if queue has no elementsO(1)

2.3 Why Not Use List pop(0)?

If you implement a queue as a list and use pop(0) to dequeue, each removal shifts all remaining elements one step – this is O(n).

Instead, Python provides collections.deque, which is optimized for fast appends and pops from both ends.

2.4 Queue Implementation with deque

Here is how to use deque for a queue:

2.5 Custom Queue Class

Here is a simple implementation of a Queue class using deque:

2.6 Real-World Uses of Queues

Queues are commonly used in various applications, such as:

HEAP · PRIORITY QUEUE

3. Heaps (Priority Queues)

A heap is a specialized tree-based data structure that satisfies the heap property. It is commonly used to implement priority queues, where elements are ordered based on priority rather than insertion order.

3.1 What is a Heap?

A heap is a special tree-based data structure that satisfies the heap property and is always a complete binary tree (all levels filled from left to right).

Two main types:

3.2 Min-Heap Example

Here is an example of a min-heap:

[ 1 ] / \ [ 3 ] [ 5 ] / \ / [ 4 ][ 6 ][ 8 ]

Min-heap property: every parent node is ≤ its children. The smallest value is always at the top.

3.3 Heaps in Python – heapq Module

Python does not have a dedicated Heap class, but the heapq module provides a very efficient min-heap implementation built on top of a list.

3.4 Basic Heap Operations with heapq

Here are the main operations using the heapq module:

3.5 Converting a List into a Heap

You can convert an existing list into a heap in-place using heapq.heapify():

3.6 Max-Heap Trick in Python

Python's heapq supports only a min-heap, but we can simulate a max-heap by pushing negative values.

3.7 Priority Queue Example

A common use of a heap is to implement a priority queue.

Output:

0 High priority
1 Low priority
2 Very low priority

3.8 Time Complexity of Heap Operations

The time complexities for key heap operations are:

OperationDescriptionTime
heappushInsert elementO(log n)
heappopRemove smallest elementO(log n)
heapifyBuild heap from listO(n)

3.9 Real-World Uses of Heaps

Heaps are widely used in various applications, such as:

4. Comparison: Stack vs Queue vs Heap

Here is a summary comparison of stacks, queues and heaps:

Feature Stack Queue Heap
Order LIFO (Last In, First Out) FIFO (First In, First Out) Priority (min or max element first)
Python Implementation list (append, pop) collections.deque heapq module
Main Use Cases Undo, recursion, DFS Scheduling, BFS, messaging Priority queues, shortest paths
Insertion append(): O(1) append(): O(1) heappush(): O(log n)
Removal pop(): O(1) popleft(): O(1) heappop(): O(log n)

5. When to Use Stack, Queue, or Heap?

Here are guidelines on when to choose each data structure:

5.1 Use a Stack when...

5.2 Use a Queue when...

5.3 Use a Heap when...