List as Stack
in Python
Master the append/pop pattern, understand LIFO ordering, and discover why Python lists give you amortized \( O(1) \) performance for stack operations.
What Is a Stack?
A stack is an abstract data type that follows the Last In, First Out (LIFO) principle. Think of a stack of plates: you can only add or remove from the top.
LIFO in Action
Why Use a Python List as a Stack?
Python has no built-in Stack class, but the built-in list already provides everything you need. Two methods are all it takes:
The append / pop Contract
Under the Hood: Dynamic Array
Python lists over-allocate memory. When the array fills up, Python creates a bigger array and copies everything over. This is the key to amortized \( O(1) \).
Amortized \( O(1) \) Explained
Most append calls are \( O(1) \): just write to the next open slot. But occasionally, the internal array is full, and Python must resize: allocate a new array (roughly \( 1.125\times \) the old size) and copy all \( n \) elements: \( O(n) \).
The Amortized Argument
Stack vs Queue
| Stack (LIFO) | Queue (FIFO) | |
|---|---|---|
| Order | Last In, First Out | First In, First Out |
| Python type | list | collections.deque |
| Add | append() | append() |
| Remove | pop() — end | popleft() — front |
| Remove cost | \( O(1) \) | \( O(1) \) with deque |
| Analogy | Stack of plates | Line at a store |
How to Apply It
stack = []stack.append(item)if stack: to avoid IndexErrorval = stack.pop()stack[-1]Example 1: Reverse a String
Example 2: Balanced Parentheses
Example 3: Undo History
Common Mistakes
Summary of Operations
| Operation | Python Code | Time | Notes |
|---|---|---|---|
| Push | stack.append(x) | Amortized \( O(1) \) | May trigger resize |
| Pop | stack.pop() | \( O(1) \) | Always constant |
| Peek | stack[-1] | \( O(1) \) | No removal |
| Is empty? | not stack | \( O(1) \) | Truthy check |
| Size | len(stack) | \( O(1) \) | Stored internally |
Question 1 of 5
What is the output of the following code?s = []
s.append(1)
s.append(2)
s.append(3)
print(s.pop(), s.pop())
Question 2 of 5
Why is list.append() described as amortized \( O(1) \) rather than worst-case \( O(1) \)?
Question 3 of 5
Which of the following operations on a Python list is NOT \( O(1) \)?
Question 4 of 5
You want to check if a string of parentheses is balanced. After processing the entire string, the stack is not empty. What does this indicate?
Question 5 of 5
What happens when you call pop() on an empty Python list?