How to Implement Stack in Python: Simple Guide and Examples
You can implement a stack in Python using a
list by using append() to push items and pop() to remove them. Alternatively, create a class with methods like push(), pop(), and peek() to manage stack behavior.Syntax
A stack can be implemented using a Python list where:
append(item)adds an item to the top of the stack (push).pop()removes and returns the top item (pop).[-1]accesses the top item without removing it (peek).
Alternatively, you can define a Stack class with these methods for clearer structure.
python
stack = [] # create an empty stack stack.append(10) # push 10 stack.append(20) # push 20 top_item = stack.pop() # pop top item (20) peek_item = stack[-1] # peek top item (10)
Example
This example shows a simple Stack class with push, pop, and peek methods to manage stack operations safely.
python
class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): if not self.is_empty(): return self.items.pop() return None # or raise error def peek(self): if not self.is_empty(): return self.items[-1] return None def is_empty(self): return len(self.items) == 0 # Using the Stack class stack = Stack() stack.push(5) stack.push(10) print(stack.peek()) # Output: 10 print(stack.pop()) # Output: 10 print(stack.pop()) # Output: 5 print(stack.pop()) # Output: None (stack is empty)
Output
10
10
5
None
Common Pitfalls
Common mistakes when implementing stacks in Python include:
- Using
pop(0)which removes from the start, making it inefficient. - Not checking if the stack is empty before popping, causing errors.
- Confusing
peekwithpopand accidentally removing items.
Always check if the stack is empty before popping or peeking to avoid exceptions.
python
stack = [] # Wrong: popping without checking if empty # This will cause IndexError if stack is empty # item = stack.pop() # Right: check before popping if stack: item = stack.pop() else: item = None # or handle empty case
Quick Reference
Stack operations summary:
| Operation | Description | Python Method/Code |
|---|---|---|
| Push | Add item to top | stack.append(item) |
| Pop | Remove and return top item | stack.pop() |
| Peek | View top item without removing | stack[-1] |
| Check Empty | See if stack has no items | len(stack) == 0 or not stack |
Key Takeaways
Use Python lists with append() and pop() to implement a stack easily.
Create a Stack class for clearer and safer stack operations.
Always check if the stack is empty before popping or peeking to avoid errors.
Avoid using pop(0) as it is inefficient for stack behavior.
Peek at the top item using stack[-1] without removing it.