Skip to content
ComputerCS
Start learning

Computational Structures · Lesson 4.1.2

Stacks: Last In, First Out

Model a stack, perform push and pop operations, and connect LIFO behaviour to undo, browser history and function-call execution.

01

Learning objectives

  • Define a stack and explain the Last In, First Out rule.
  • Trace push, pop, peek and is-empty operations.
  • Recognise stack overflow and underflow conditions.
  • Identify practical situations naturally modelled by stacks.
02

Lesson notes

A stack stores items in a sequence but restricts ordinary access to one end called the top. The most recently inserted item is removed first, so a stack follows Last In, First Out (LIFO). Think of a pile of plates: the top plate is the first one you can remove without disturbing the rest.

Push inserts an item at the top, pop removes and returns the top item, and peek reads the top without removing it. is_empty checks whether there are any items. Popping an empty stack causes underflow; pushing beyond a fixed-capacity implementation can cause overflow. The exact error policy depends on the implementation.

Stacks appear in undo and redo systems, navigation history, expression evaluation, bracket matching and the program call stack. When one function calls another, execution state is saved so the program can return to the correct location after the nested call finishes.

A Python list can implement a simple stack using append for push and pop for removal at the end. Operations at the end are efficient for this use. The interface matters more than the storage detail: a stack user should not depend on arbitrary access to middle elements.

03

Worked code examples

Worked example

The last pushed value is the first popped value, demonstrating LIFO behaviour.

stack = []
stack.append("open")
stack.append("save")
print("Top:", stack[-1])
print("Removed:", stack.pop())
print("Remaining:", stack)
Output
Top: save
Removed: save
Remaining: ['open']
04

Key terminology

Stack

A linear structure that removes the most recently inserted item first.

Push

Insert an item at the top of a stack.

Pop

Remove and return the top item.

Underflow

Attempting to remove an item from an empty structure.

05

Common misconceptions

Common mistake

A stack removes the oldest item first.

Correct understanding

That is FIFO queue behaviour; a stack is LIFO.

Common mistake

Pop and peek mean the same thing.

Correct understanding

Pop removes the top item; peek reads it without removing it.

06

Check your understanding

1. Which principle describes a stack?

2. Which operation reads the top item without removing it?

3. Trying to pop an empty stack is called:

NERDLYY · FEEDBACK

Help shape Nerdlyy

Your feedback goes directly to the team. We read every submission.

No reply needed — you can send feedback without sharing contact details.