How to Implement Stack Using List in Python: Simple Guide
You can implement a stack in Python using a
list by using append() to add items (push) and pop() to remove items (pop) from the end of the list. This mimics the Last-In-First-Out (LIFO) behavior of a stack.Syntax
A stack using a Python list uses these main operations:
- Push: Add an item to the top with
list.append(item). - Pop: Remove the top item with
list.pop(). - Peek: Look at the top item with
list[-1]without removing it.
python
stack = [] # create an empty stack stack.append(10) # push 10 stack.append(20) # push 20 top_item = stack.pop() # pop returns 20 peek_item = stack[-1] # peek returns 10
Example
This example shows how to create a stack, push items, pop an item, and peek at the top item.
python
stack = [] # Push items stack.append('apple') stack.append('banana') stack.append('cherry') print('Stack after pushes:', stack) # Pop item popped = stack.pop() print('Popped item:', popped) # Peek at top item top = stack[-1] print('Top item now:', top)
Output
Stack after pushes: ['apple', 'banana', 'cherry']
Popped item: cherry
Top item now: banana
Common Pitfalls
Common mistakes when using a list as a stack include:
- Using
pop(0)which removes from the start and is slow. - Trying to peek when the stack is empty, causing an
IndexError. - Modifying the list directly without using
appendorpop, breaking stack behavior.
Always check if the stack is empty before popping or peeking.
python
stack = [] # Wrong: popping from empty stack causes error # popped = stack.pop() # IndexError # Right: check before popping if stack: popped = stack.pop() else: popped = None print('Popped:', popped)
Output
Popped: None
Quick Reference
| Operation | Method | Description |
|---|---|---|
| Push | list.append(item) | Add item to top of stack |
| Pop | list.pop() | Remove and return top item |
| Peek | list[-1] | View top item without removing |
| Check Empty | if not list | Check if stack is empty |
Key Takeaways
Use list.append() to push items onto the stack.
Use list.pop() to pop items from the stack safely.
Peek the top item with list[-1] but check if stack is not empty first.
Avoid popping from an empty stack to prevent errors.
Using a list as a stack is simple and efficient for LIFO behavior.