Module 5 · Stacks, Queues and Linked Lists · Lesson 14 of 40

Stacks: last in, first out

A pile where you add and remove only at the top. Used for undo, brackets and the function call stack.

In this lesson · about 20 minutes

  • Use a Python list as a stack with append and pop
  • Explain LIFO with an everyday example
  • Check whether brackets are balanced

A stack is like a pile of plates. You put a plate on the top, and you take a plate from the top. The last plate you added is the first one you take off. This rule is called LIFO: Last In, First Out.

ActionMeaningPython listCost
pushAdd to the topstack.append(x)O(1)
popRemove from the topstack.pop()O(1)
peekLook at the topstack[-1]O(1)
is empty?Nothing left?not stackO(1)

Popping an empty stack is an error called underflow. Always check if stack: first.

Where stacks appear

  • The Undo button: the last change is undone first.
  • The browser's Back button.
  • Function calls: Python keeps waiting calls on a call stack.
  • Checking brackets in code or maths.

Try it · see it work

Stack vs queue

For now, look at the stack on the left. Add a few letters, then pop. Which comes out first?

Stack (LIFO), like a pile of plates

AB ← top

Queue (FIFO), like a line at a shop

front →AB← back

Add the same items to both, then remove one from each. Which item leaves first?

Balanced brackets

Is "( [ ] { } )" balanced? Yes. Is "( ]"? No. A stack solves this neatly:

  1. When you see an opening bracket ( [ {, push it.
  2. When you see a closing bracket, the top of the stack must be its partner. If it is, pop it. If not (or the stack is empty), the brackets are not balanced.
  3. At the end, the stack must be empty.

Try it: a stack in action

Exercise

Balanced brackets

Write is_balanced(s) that returns True if every bracket in s is closed in the right order. Only the characters ()[]{} appear.

Check your understanding0 of 3 correct

Question 1

1.Push A, push B, push C, then pop. What comes out?

Question 2

2.Which Python line looks at the top of a stack without removing it?

Question 3

3.What is popping an empty stack called?

Quiz score: 0 of 3

Exercises solved: 0 of 1

Tip: answer every quiz question correctly first.

Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.