Implement a Stack Using List Push Pop in Python

A minimal Stack class built on a Python list, with push, pop, peek, is_empty, and size methods, including empty-stack guards.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 12 views 0 copies

Python code

36 lines
Python 3.9+
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):
        if self.is_empty():
            raise IndexError("peek from empty stack")
        return self.items[-1]

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

    def size(self):
        return len(self.items)


if __name__ == "__main__":
    stack = Stack()
    stack.push(10)
    stack.push(20)
    stack.push(30)

    print("Size:", stack.size())
    print("Top:", stack.peek())
    print("Pop:", stack.pop())
    print("Pop:", stack.pop())
    print("Empty?", stack.is_empty())
    print("Size:", stack.size())

Output

stdout
Size: 3
Top: 30
Pop: 30
Pop: 20
Empty? False
Size: 1

How it works

This stack uses a Python list as the underlying store. push appends to the end, and pop removes from the end, giving O(1) amortized operations. peek returns the last element without removing it. Guard clauses raise IndexError on empty-stack access to avoid silent bugs. The is_empty and size methods provide the standard stack interface.

Common mistakes

  • Forgetting to guard `pop` or `peek` and letting an internal `IndexError` leak
  • Confusing `append`/`pop` with `insert(0, ...)`/`pop(0)`, which would be O(n)
  • Using `if not self.items` instead of `is_empty()` may be clearer but also fine

Variations

  1. Implement the same interface with `collections.deque` for thread-safety or when frequent resizing matters
  2. Add a `__len__` method so `len(stack)` works directly

Real-world use cases

  • Undo/redo history in editors or design tools, where only the most recent action is reverted.
  • Parsing matched delimiters (brackets, braces) in a text linter or compiler front-end.
  • Backtracking in maze solvers or depth-first search traversal of a graph.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.