01 / 20

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.

Python Data Structures

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.

Push
Add an element to the top of the stack.
Pop
Remove and return the top element from the stack.
Peek
Look at the top element without removing it.

LIFO in Action

"A" "B" "C" "D" ← TOP push pop BOTTOM

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:

list.append(x)
Pushes \(x\) onto the end (top) of the list. Amortized \( O(1) \).
list.pop()
Removes and returns the last (top) item. \( O(1) \) every time.

The append / pop Contract

stack = [] # Push elements stack.append(10) # [10] stack.append(20) # [10, 20] stack.append(30) # [10, 20, 30] # Pop elements (LIFO order) stack.pop() # returns 30 → [10, 20] stack.pop() # returns 20 → [10] # Peek at top without removing top = stack[-1] # 10

Under the Hood: Dynamic Array

10 [0] 20 [1] 30 [2] — [3] — [4] — [5] Used (len = 3) Allocated (capacity = 6) len(stack) = 3 internal capacity = 6 TOP

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) \).

append call number cost O(n) O(n) O(n) O(1) normal O(n) resize

The Amortized Argument

1
Start with capacity \( c \). After \( c \) appends, the array is full.
2
Resize to \( \approx 1.125c \). Python copies \( c \) elements: cost \( O(c) \).
3
Spread the cost. That single \( O(c) \) copy is "charged" across the \( c \) cheap appends that came before it.
4
Each append "pays" a constant extra. Total cost for \( n \) appends is \( O(n) \), so each one averages \( O(1) \).

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

1
Initialize an empty list: stack = []
2
Push with append: stack.append(item)
3
Check before pop: if stack: to avoid IndexError
4
Pop from top: val = stack.pop()
5
Peek without removing: stack[-1]

Example 1: Reverse a String

def reverse_string(s): stack = [] for ch in s: stack.append(ch) result = "" while stack: result += stack.pop() return result print(reverse_string("hello")) # "olleh"

Example 2: Balanced Parentheses

def is_balanced(expr): stack = [] pairs = {")": "(", "]": "[", "}": "{"} for ch in expr: if ch in "([{": stack.append(ch) elif ch in pairs: if not stack or stack.pop() != pairs[ch]: return False return not stack

Example 3: Undo History

class TextEditor: def __init__(self): self.text = "" self.history = [] # stack of previous states def write(self, s): self.history.append(self.text) # save state self.text += s def undo(self): if self.history: self.text = self.history.pop()

Common Mistakes

✕ Using pop(0)
pop(0) removes from the front: \( O(n) \) because every remaining element shifts. Use pop() with no argument for the stack top.
✕ Popping empty list
Calling pop() on an empty list raises IndexError. Always check if stack: first.
✕ Using insert(0, x)
insert(0, x) pushes to the front: \( O(n) \) shift. For a stack, append(x) is the correct push operation.

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?