Implementing Stack with Python
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
A stack is one of the simplest and most useful data structures in programming. It follows the Last In, First Out rule, which means the most recently added item is the first one removed. That behavior shows up everywhere, from function-call management to undo systems and expression parsing.
Python makes stack implementation straightforward, but there is still value in being explicit about the operations and tradeoffs. A good stack interface should make push, pop, peek, and emptiness checks obvious, and it should fail predictably when the caller pops from an empty structure.
Use a List for the Simplest Stack
For most Python programs, a plain list is a perfectly good stack. Appending to the end and popping from the end are both efficient operations.
This is the simplest implementation because Python lists already give you the exact operations a stack needs.
A few rules keep this safe:
- use
appendfor push - use
popwith no index for pop - use
stack[-1]only after checking the stack is not empty
Avoid insert(0, value) and pop(0) for stack behavior. Those act on the front of the list and are slower because the remaining items have to shift.
Wrap the Behavior in a Class
If the stack is part of a larger program, a small class makes the interface clearer and protects callers from working with raw list internals.
Usage stays clean:
This pattern is useful when you want a stable API, type hints, logging, or validation around stack operations.
deque Is Another Good Option
The standard library also provides collections.deque, which is excellent when you need fast push and pop operations from either end.
For a pure stack, list and deque are both reasonable. Lists are simpler and very common. deque becomes especially attractive when the same structure might later need queue-like behavior as well.
A Practical Example: Balanced Parentheses
Stacks are easiest to understand when they solve a real problem. A classic example is checking whether parentheses are balanced.
This works because the most recent opening bracket must match the next closing bracket, which is exactly a Last In, First Out rule.
Think About Error Handling
An empty-stack pop is not just a small edge case. It is part of the interface contract. Decide early whether your stack should raise an exception, return None, or use a sentinel value.
Raising IndexError is the most Pythonic default because it clearly signals misuse and matches existing sequence behavior. Returning None is sometimes convenient, but it can hide bugs if None is also a valid value.
If you add type hints, the contract becomes even clearer:
You can then build a generic stack class if the project benefits from stronger typing.
Common Pitfalls
The most common mistake is using the front of a list as the top of the stack. That works functionally, but it is a poorer performance choice than using the end.
Another mistake is peeking or popping without handling the empty case. Stack code often sits inside parsers and evaluators, so a clear error message matters.
A third issue is exposing the backing list publicly and letting other parts of the program mutate it directly. That defeats the point of having a stack abstraction.
Summary
- A stack follows the Last In, First Out rule.
- In Python, a list with
appendandpopis the simplest stack implementation. - A small class makes the interface clearer for larger programs.
- '
collections.dequeis also a strong option for stack behavior.' - Always define what should happen when callers pop or peek on an empty stack.
Related reading
- ImportError cannot import name 'set_random_seed' from 'tensorflow' CUserspolonAnaconda3libsite-packagestensorflow__init__.py
- In-graph replication vs Between-graph replication
- In-order iterator for binary tree
- In-place array reordering?
- Import a module from a relative path
- Import error No module name urllib2
- in-place permutation of a array follows this rule
- In-Place Radix Sort

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.