Sub topic 8
Using stacks from the standard library
This chapter assumes you can write the array-backed Stack class from earlier and that you know Big-O notation. Here you will see which built-in types to use as a stack in Python, Java, and JavaScript, and which ones to avoid.
Python: use a list or a deque
Python has no dedicated stack class. A list works because append and pop act on the end of the list in amortized O(1) time.
stack = []
stack.append("a") # push
stack.append("b")
print(stack[-1]) # peek -> b
print(stack.pop()) # pop -> b
print(not stack) # is_empty -> FalseCalling pop() on an empty list raises IndexError. Calling stack[-1] on an empty list raises it too. Check if stack: first if the empty case is expected.
collections.deque is the other common choice. It supports append and pop at the right end in O(1) time. It never copies its contents to a larger array, so it has no occasional slow resize.
from collections import deque
stack = deque()
stack.append(1)
stack.append(2)
print(stack.pop()) # 2
print(stack[-1]) # 1Do not use list.insert(0, x) and list.pop(0) to build a stack at the front. Each call shifts every element and costs O(n).
Java: prefer Deque over Stack
Java has a class named java.util.Stack. It extends Vector, so it is synchronized and exposes methods such as get(i) and add(i, x) that break the stack idea. The Java documentation recommends Deque instead.
import java.util.ArrayDeque;
import java.util.Deque;
public class Demo {
public static void main(String[] args) {
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1);
stack.push(2);
System.out.println(stack.peek()); // 2
System.out.println(stack.pop()); // 2
}
}pop() throws NoSuchElementException on an empty deque. peek() returns null instead. ArrayDeque does not allow null elements, so a null result always means the stack is empty.
JavaScript: arrays
A JavaScript Array is a stack through push and pop. Both work on the end. pop on an empty array returns undefined and does not throw, so you must check length yourself when undefined could be a valid value.
const stack = [];
stack.push(1);
stack.push(2);
console.log(stack[stack.length - 1]); // 2
console.log(stack.pop()); // 2Comparing the options
| Language | Recommended type | Push | Pop | Pop on empty |
|---|---|---|---|---|
| Python | `list` or `deque` | `append` | `pop` | `IndexError` |
| Java | `ArrayDeque` | `push` | `pop` | `NoSuchElementException` |
| JavaScript | `Array` | `push` | `pop` | returns `undefined` |
Common mistakes
- Using
java.util.Stackin new code. It carries the overhead of synchronization and a wider interface than a stack needs. - Treating a list's front as the top. This makes every push and pop O(n).
- Forgetting the empty case. Each language reports it differently, as the table shows.
- Sharing a plain
listordequebetween threads and assuming that compound steps like "check empty, then pop" are safe. They are not atomic.
Exercise
A teammate writes a Python stack with items.insert(0, x) for push and items.pop(0) for pop. The code returns correct results. What is wrong with it, and what is the fix?
Show answer
Each insert at index 0 and pop at index 0 shifts every other element, so each operation costs O(n) instead of O(1). The fix is to push and pop at the end with append and pop(), or to use a collections.deque with append and pop.
Exercise
In Java, what is the difference between pop() and peek() on an empty ArrayDeque used as a stack?
Show answer
pop() throws NoSuchElementException, while peek() returns null.