0
0
Data-structures-theoryConceptBeginner · 3 min read

What is LIFO in Stack: Explanation and Examples

LIFO stands for Last In, First Out, a principle where the last element added to a stack is the first one to be removed. In a stack, items are added and removed only from the top, making it work like a stack of plates where you take the top plate first.
⚙️

How It Works

A stack is a collection where you can only add or remove items from one end, called the top. The LIFO principle means the last item you put on the stack is the first one you take off. Imagine a stack of books: if you add a new book on top, you must remove that top book before you can get to the ones below.

This behavior is useful because it keeps things organized in a simple way. You don't have to search through the stack to find an item; you always deal with the most recent one first. This is different from a queue, where the first item added is the first one removed.

💻

Example

This example shows how a stack works using LIFO. We add three numbers and then remove them one by one, showing that the last number added is removed first.

python
class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        if not self.is_empty():
            return self.items.pop()
        return None

    def is_empty(self):
        return len(self.items) == 0

stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)

print(stack.pop())  # Outputs 3
print(stack.pop())  # Outputs 2
print(stack.pop())  # Outputs 1
Output
3 2 1
🎯

When to Use

Use a stack with LIFO when you need to reverse things or keep track of recent actions. For example, undo features in text editors use stacks to remember the last changes so you can undo them in reverse order. Another use is in web browsers to manage the history of pages you visit, allowing you to go back step-by-step.

Stacks are also important in programming for managing function calls and expressions, where the most recent call or operation must be completed before returning to earlier ones.

Key Points

  • LIFO means the last item added is the first removed.
  • Stacks only allow adding/removing from the top.
  • Useful for undo actions, browser history, and function calls.
  • Works like a stack of plates or books.

Key Takeaways

LIFO means the last item added to a stack is the first one removed.
Stacks operate by adding and removing items only from the top.
Stacks are useful for undo features, browser history, and managing function calls.
Think of a stack like a pile of plates where you take the top plate first.