A stack is a last-in, first-out structure. The most recently added item is the first item removed.
Stacks are useful when the algorithm needs to remember unfinished work and return to the most recent item first.
Core Idea
The main operations are push and pop. In Python, a list usually acts as a stack: append pushes and pop removes the most recent item.
This behavior matches nested structure. Function calls, parentheses, depth-first search, and backtracking all have stack-like behavior.
Python Example
stack = []
stack.append("open")
stack.append("work")
last = stack.pop()After the pop, last is "work" because it was added most recently.
Common Confusions
A stack is defined by behavior, not by a specific class. In Python, a plain list is often enough.
Do not use pop(0) for stack behavior. That removes the oldest item, not the newest item, and it is also inefficient for Python lists.
When To Use It
Use a stack for nested or reversible work: matching parentheses, evaluating expressions, iterative DFS, undo-like behavior, and algorithms that need to postpone choices until later.