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.
Python code
36 linesclass 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
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
- Implement the same interface with `collections.deque` for thread-safety or when frequent resizing matters
- 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
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.