Facebook Pixel

Stack - The LIFO Model

The Stack of Plates

A stack works like a stack of plates in a cafeteria. You add new plates on top. When you need a plate, you take from the top. The last plate you added is the first one you remove.

This is Last-In-First-Out (LIFO). The most recent item goes out first.

Stack of Plates

Browser Back Button

Your browser's back button uses a stack. Every page you visit gets pushed onto a stack. When you click back, the browser pops the most recent page. Click back again, and you get the page before that.

Visit pages: Home → Products → Cart

  • Stack: [Home, Products, Cart]

Click back:

  • Pop Cart, now at Products
  • Stack: [Home, Products]

Click back again:

  • Pop Products, now at Home
  • Stack: [Home]

Browser History Stack

The last page visited is the first page returned to. That's LIFO in action.

Core Stack Operations

A stack has two fundamental operations:

  • Push: Add an element to the top of the stack
  • Pop: Remove the element from the top of the stack

Some stacks also provide:

  • Peek: Look at the top element without removing it
  • isEmpty: Check if the stack has any elements

Stack Operations

1# Using Python list as a stack
2stack = []
3
4# Push elements
5stack.append(10)
6stack.append(20)
7stack.append(30)
8# Stack: [10, 20, 30] (30 is on top)
9
10# Pop element
11top = stack.pop()  # Returns 30
12# Stack: [10, 20]
13
14# Peek at top
15if stack:
16    top_element = stack[-1]  # Returns 20 without removing

Python lists provide append() for push and pop() for pop.

Last In, First Out

The defining characteristic of a stack is LIFO order. Whatever you put in last comes out first. This is different from a queue, which is First-In-First-Out (FIFO).

Add items: A, B, C

  • Stack: [A, B, C] (C on top)

Remove items:

  • First pop: C
  • Second pop: B
  • Third pop: A

The order reverses. Items come out in the opposite order they went in.

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro