Python Stacks


A stack is one of the simplest and most important data structures in programming. It works on the LIFO rule, which means Last In, First Out. The item you add last is the one that comes out first. This pattern appears everywhere in real systems, from undo features in apps to browser history, call operations in Python and even memory management.

In this chapter, you will understand what a stack is, how it works, how to build stacks using Python lists, how to implement them using the collections module and how stacks appear in real-world applications. You will also practice common operations such as push, pop, peek and checking if a stack is empty. The goal is to help you use stacks confidently in both small programs and larger data-handling tasks.

What Is a Stack?

A stack is a linear data structure where elements are added and removed from the same end. This end is called the top of the stack.

A simple way to imagine a stack is a pile of plates. You place new plates on top and remove plates from the top. You cannot remove from the middle or bottom without disturbing the stack.

Stacks follow two main operations:

  • Push: Add an item to the top

  • Pop: Remove an item from the top

Every stack also allows checking the top element and checking whether the stack is empty.

What is the LIFO Concept?

LIFO stands for Last In, First Out. This rule decides how items move in and out of a stack.

Example scenario:

  1. You push 10

  2. You push 20

  3. You push 30

Now the stack looks like this (top → bottom): 30, 20, 10

If you pop, you will get 30 first.

This makes stacks perfect for tasks where the most recent action needs to be undone or reversed.

Creating a Stack Using Python Lists

The simplest way to create a stack in Python is to use a list. The append() method performs push and the pop() method performs pop.

stack = []

stack.append(10)
stack.append(20)
stack.append(30)

print(stack)

When you pop:

value = stack.pop()
print(value)

This removes the top element and returns it.

Push Operation

Push adds a new value at the end:

stack.append(40)

This is useful in tasks like saving browser history or adding steps in an undo feature.

Pop Operation

Pop removes and returns the most recent value:

item = stack.pop()

This helps reverse processes, step back through changes or manage temporary operations.

Peek Operation

Peek means checking the top element without removing it.

top = stack[-1]
print(top)

This is helpful when you need to inspect what is next without changing the stack.

Checking If Stack Is Empty

Empty stacks help prevent errors during pop operations.

if not stack:
    print("Stack is empty")
else:
    print("Stack has items")

This is important for safe coding in programs where user input or external systems control flow.

Using collections.deque for Faster Stacks

While lists work well, Python’s deque from the collections module provides faster append and pop operations for large stacks.

from collections import deque

stack = deque()

stack.append(10)
stack.append(20)
stack.append(30)

print(stack.pop())

deque is a good choice when working with large or performance-heavy data.

Implementing a Stack Class

You can create a simple class to manage stack operations in a cleaner way.

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

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

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

    def peek(self):
        if not self.items:
            return None
        return self.items[-1]

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

This structure is helpful when building larger applications where stacks are a core part of the logic.

Real-Life Uses of Stacks

Stacks appear in many everyday programming tasks:

Undo/Redo in Editors

Each change you make is stored in a stack. When you undo, the editor pops the last action.

Browser History

Each visited page is pushed to a stack. Pressing back pops the last page.

Function Calls in Python

Every function call is stored in a call stack. When a function ends, Python pops it.

Expression Evaluation

Stacks help evaluate arithmetic expressions and manage operator order.

Parentheses Matching

Stacks help validate brackets in code editors and compilers.

These examples show why stacks are one of the most essential data structures.

Reversing Data With a Stack

You can reverse a string using a stack.

text = "hello"
stack = []

for ch in text:
    stack.append(ch)

rev = ""
while stack:
    rev += stack.pop()

print(rev)

This matches how many systems handle reverse operations internally.

Balanced Parentheses Example

A common use of stacks is checking if brackets match correctly.

def is_balanced(expr):
    stack = []
    for ch in expr:
        if ch in "({[":
            stack.append(ch)
        elif ch in ")}]":
            if not stack:
                return False
            stack.pop()
    return not stack

This logic appears in compilers, text editors and linters.

Practical Examples

Example 1: Create empty stack

stack = []

Example 2: Push items

stack.append(10)

Example 3: Pop item

item = stack.pop()

Example 4: Peek top value

top = stack[-1]

Example 5: Check empty

len(stack) == 0

Example 6: Reverse a list

result = []
while stack:
    result.append(stack.pop())

Example 7: Using deque

from collections import deque
stack = deque()

Example 8: Pushing multiple values

for i in range(5):
    stack.append(i)

Example 9: Stack class usage

s = Stack()
s.push(50)

Example 10: Pop safely

if stack:
    stack.pop()

Summary of the Tutorial

A stack is a simple but powerful structure based on the LIFO rule. You learned how stacks work, how to push and pop values, how to peek at the top and how to handle empty conditions. You also explored deque for performance, created a custom stack class and saw real-life uses like undo actions, browser history, function calls and expression checking. Stacks form the foundation for more complex structures like queues, linked lists, trees and even recursion. Once you understand stacks, you will find many places where they fit naturally into your Python work.


Practice Questions

Q1. Write a Python program to create an empty stack and add three items to it.

Q2. Write a Python program to remove the last added item using pop().

Q3. Write a Python program to check the top item in the stack without removing it.

Q4. Write a Python program to print all items in a stack using a loop.

Q5. Write a Python program to use collections.deque to push and pop names.

Q6. Write a Python program to count the number of items in a stack using len().

Q7. Write a Python program to create a stack and remove all items one by one using a loop.

Q8. Write a Python program to use a stack to reverse a string.

Q9. Write a Python program to check if the stack is empty and print a message accordingly.

Q10. Write a Python program to push and pop elements in numeric order and display the stack content at each step.


Try a Short Quiz.

Python Stacks Quiz

Finished the tutorial? Play this medium-level quiz to strengthen your concepts.


Go Back Top