Data Structures #5: Stack

What is a Stack

Think of a stack of clean trays in a cafeteria. When you need one, you always take the tray right off the top. You wouldn't try to pull one out from the middle or the bottom—that would be a mess! The tray that was put on the pile last is the very first one to be picked up.

This is exactly how a Stack works in programming. It follows a simple rule called LIFO, which stands for Last-In, First-Out. It’s like a "one-way" storage system where you can only add or remove things from the very top. Whether it’s hitting "Undo" on your keyboard or clicking the "Back" button on your browser, you're just grabbing the last thing you did from the top of the stack.


The Stack under the hood

In a Stack, you only need to worry about two main moves. Imagine you have a narrow container where you can only drop things in from the top.

  • Push: This is just a fancy word for adding something to the top of the pile.
  • Pop: This means removing the item that’s currently on the very top.

Because you can only get to the top item, you don't have to go searching through the whole pile. It’s quick, organized, and predictable.


Example


# 1. Create an empty stack (a list)
my_stack = []

# 2. PUSH: Adding items to the top
my_stack.append("Book A")
my_stack.append("Book B")
my_stack.append("Book C")

print("Stack after pushing:", my_stack)
# Output: ['Book A', 'Book B', 'Book C'] - C is on top!

# 3. POP: Removing the item from the top
top_item = my_stack.pop()

print("Item removed:", top_item)
# Output: Book C

print("Stack now:", my_stack)
# Output: ['Book A', 'Book B']
                                        

When it is used

The applications of a stack are almost everywhere but we don't really see it. The most common use is in undo/redo functionality in text editors Another use is browser history when we press the back button. Even in compilers use stack. Where you think the famous "Stack Overflow" came from?