Skip to content
prdlk
Esc
↑↓navigate↵open⌘Jpreview
On this page

Stack

Items are added and removed from one end, so the last item added is the first item removed.

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.

Core Stack Operations

A stack has two fundamental operations:

  • Push: add an item to the top of the stack
  • Pop: remove the item at the top of the stack

Some stacks have additional operations:

  • Peek: get the item at the top of the stack without removing it
  • IsEmpty: check if the stack is empty

# Using Python list as a stack
stack = []

# Push elements
stack.append(10)
stack.append(20)
stack.append(30)
# Stack: [10, 20, 30] (30 is on top)

# Pop element
top = stack.pop()  # Returns 30
# Stack: [10, 20]

# Peek at top
if stack:
    top_element = stack[-1]  # Returns 20 without removing

Python lists provide append() for pushing and pop() for popping. The peek() method is not built-in, but you can implement it yourself.

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.

Last updated on

Was this page helpful?