Python Algorithms

Stack Data Structure in Python

A stack follows last in, first out order: the most recently added value is removed first.

What is Stack Data Structure?

A stack follows last in, first out order: the most recently added value is removed first.

Implement push, pop, and peek operations with a Python list.

When should you use it?

  • Practice problem solving and data structures.
  • Process data when every algorithm step must be explicit.
  • Prepare for programming exercises, exams, and interviews.

Example code

Run code →
main.py
stack = []
stack.append("first")
stack.append("second")
stack.append("third")

print("popped:", stack.pop())
print("top:", stack[-1])
print("stack:", stack)

Expected output

popped: third
top: second
stack: ['first', 'second']

How it works

List append pushes onto the top and pop removes from the same end. Both operations are O(1) amortized.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Try empty, single-item, and duplicate-value inputs.
  2. Print state after every step to observe the algorithm.
  3. Benchmark 100, 1,000, and 10,000 items, then compare another approach.
Run in Python IDE →