Skip to main content

What is a Stack?

A Stack is a Last In, First Out (LIFO) data structure — the last element added is the first element removed, just like a stack of plates.
A stack can be implemented using either arrays or linked lists.

Key Operations

OperationDescriptionBig-O
PushAdd an element to the top of the stackO(1)
PopRemove and return the top elementO(1)
Peek / TopReturn the top element without removing itO(1)

Advantages

  • Simple to implement with O(1) push and pop
  • Efficient for depth-first search and backtracking
  • Well-suited for recursion, expression evaluation, and undo/redo

Disadvantages

  • Only the top element is directly accessible
  • Fixed size if implemented with a static array
  • Not suitable for random access
  • Can cause underflow if popping from an empty stack

Real-World Applications

  • Undo / Redo functionality in text editors
  • Browser history (back/forward navigation)
  • Recursion call stack management
  • Expression evaluation and syntax parsing

Stack Implementation

The simplest approach — use Python’s built-in list.append() and list.pop() which both operate in O(1).
stack.py
class Stack:
    def __init__(self) -> None:
        self.items = []

    def __len__(self) -> int:
        return len(self.items)

    def __str__(self) -> str:
        return str(self.items)

    def is_empty(self) -> bool:
        return len(self.items) == 0

    def push(self, item: int) -> None:
        self.items.append(item)

    def pop(self) -> int:
        if self.is_empty():
            raise IndexError("Stack Underflow: Cannot pop from an empty stack")
        return self.items.pop()

    def peek(self) -> int:
        if self.is_empty():
            raise IndexError("Stack Underflow: Cannot peek an empty stack")
        return self.items[-1]

stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)

print(len(stack))    # 3
print(stack)         # [1, 2, 3]
print(stack.pop())   # 3
print(stack.peek())  # 2
print(stack)         # [1, 2]

Build docs developers (and LLMs) love