Python · Module 12 · Lesson 21 min read

Core Data Structures

Pick the right container

StructurePythonStrength
Dynamic arraylistfast index access, append
Stack (LIFO)list (append / pop)undo, back button, brackets
Queue (FIFO)collections.dequetask queues, BFS
Hash mapdictfast key lookup
Setsetuniqueness, fast membership
Heap / priority queueheapqalways get the smallest first
Linked listcustom classO(1) insert/remove at a known node

Stack vs queue

  • Stack: last in, first out, like a pile of plates.
  • Queue: first in, first out, like a line at a shop. Don't use list.pop(0) for queues; it's O(n). deque.popleft() is O(1).

Building your own

Writing a stack or linked list yourself is a classic exercise and a common interview question. In real code, prefer the built-ins.

▶️ Runs in the app.

Example

Python
from collections import deque
import heapq

class Stack:
    def __init__(self):
        self._items = []
    def push(self, item):
        self._items.append(item)
    def pop(self):
        if self.is_empty():
            raise IndexError("pop from empty stack")
        return self._items.pop()
    def peek(self):
        return self._items[-1] if self._items else None
    def is_empty(self):
        return not self._items

def balanced(text):                   # classic stack problem
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = Stack()
    for ch in text:
        if ch in "([{":
            stack.push(ch)
        elif ch in pairs:
            if stack.is_empty() or stack.pop() != pairs[ch]:
                return False
    return stack.is_empty()

print(balanced("{[()]}"), balanced("(]"))   # True False

queue = deque(["a", "b"])
queue.append("c")
print(queue.popleft())                # a  (O(1))

tasks = [(3, "low"), (1, "urgent"), (2, "normal")]
heapq.heapify(tasks)
print(heapq.heappop(tasks))           # (1, 'urgent')