DEV Community

Minh Vu
Minh Vu

Posted on

How to Implement a Stack in Python

Introduction

Stack is a fundamental data structure in computer science and programming that allows you to store and retrieve elements in a specific order. In Python programming, you can easily implement a stack data structure using a list or a deque class from the collections module. Understanding how to implement a stack in Python is essential for any Python developer who wants to write efficient and robust code.

In this article, we will provide you with a step-by-step guide on how to implement a stack in Python. We will also give you some examples of how to use the stack data structure in real-world Python applications. By the end of this article, you will have a solid understanding of how to implement a stack in Python and how it can be used to solve programming problems. So, let's dive in!

You can read the full article at WiseCode Blog.

Stack Implementation in Python

To implement a stack in Python, we can define a stack class that has two fundamental methods: push and pop. The push method adds a new element to the top of the stack, while the pop method removes and returns the top element from the stack. Here's a step-by-step guide to implementing a stack in Python:

  1. Define a stack class using the class keyword.
class Stack:
    def __init__(self):
        self.stack = []
Enter fullscreen mode Exit fullscreen mode
  1. In the __init__ method, initialize an empty list to store the stack elements.

  2. Implement the push method, which takes an element as an argument and adds it to the top of the stack using the append method.

def push(self, element):
    self.stack.append(element)
Enter fullscreen mode Exit fullscreen mode
  1. Implement the pop method, which removes and returns the top element from the stack using the pop method.
def pop(self):
    if not self.is_empty():
        return self.stack.pop()
    else:
        return "Stack is empty"
Enter fullscreen mode Exit fullscreen mode
  1. Implement the is_empty method, which returns True if the stack is empty and False otherwise.
def is_empty(self):
    return len(self.stack) == 0
Enter fullscreen mode Exit fullscreen mode
  1. Implement the peek method, which returns the top element from the stack without removing it.
def peek(self):
    if not self.is_empty():
        return self.stack[-1]
    else:
        return "Stack is empty"
Enter fullscreen mode Exit fullscreen mode
  1. Handle the stack overflow and underflow errors by checking the stack size before pushing or popping elements.
MAX_SIZE = 5
def push(self, element):
    if len(self.stack) == MAX_SIZE:
        return "Stack is full"
    else:
        self.stack.append(element)

def pop(self):
    if not self.is_empty():
        return self.stack.pop()
    else:
        return "Stack is empty"
Enter fullscreen mode Exit fullscreen mode

That's it! Now you have a fully functional stack implementation in Python. In the next section, we will give you some examples of how to use the stack data structure in Python programming.

Python Stack Examples

Now that we have implemented a stack data structure in Python, let's see some examples of how to use it in programming. Here are some common use cases for stacks:

Example 1: Balanced Parentheses

One of the most common applications of a stack is checking for balanced parentheses in an expression. This problem can be solved using a stack by pushing the opening parentheses onto the stack and popping them off as closing parentheses are encountered.

def is_balanced(expr):
    stack = Stack()
    for char in expr:
        if char in ['(', '{', '[']:
            stack.push(char)
        elif char in [')', '}', ']']:
            if stack.is_empty():
                return False
            current_char = stack.pop()
            if current_char == '(' and char != ')':
                return False
            if current_char == '{' and char != '}':
                return False
            if current_char == '[' and char != ']':
                return False
    return stack.is_empty()
Enter fullscreen mode Exit fullscreen mode

Example 2: Reversing a String

Another common use case for stacks is reversing a string. We can push each character of the string onto the stack and then pop them off to get the reversed string.

def reverse_string(string):
    stack = Stack()
    for char in string:
        stack.push(char)
    reversed_string = ""
    while not stack.is_empty():
        reversed_string += stack.pop()
    return reversed_string
Enter fullscreen mode Exit fullscreen mode

Example 3: Depth-First Search

Depth-First Search (DFS) is a graph traversal algorithm that uses a stack to keep track of the nodes to visit. We start by pushing the initial node onto the stack, and then popping off nodes and pushing their neighbors onto the stack until we have visited all the nodes in the graph.

def depth_first_search(graph, start):
    visited = set()
    stack = Stack()
    stack.push(start)
    while not stack.is_empty():
        current_node = stack.pop()
        if current_node not in visited:
            visited.add(current_node)
            for neighbor in graph[current_node]:
                stack.push(neighbor)
    return visited
Enter fullscreen mode Exit fullscreen mode

These are just a few examples of how stacks can be used in Python programming. With this knowledge, you can now start implementing stacks in your own projects!

Conclusion

In this article, we have learned how to implement a stack data structure in Python. We started by understanding what a stack is and how it works. Then, we went on to implement a stack using a Python list and using a custom Stack class.

We also explored some common use cases for stacks in Python programming, including checking for balanced parentheses, reversing a string, and depth-first search.

By understanding how stacks work and how to use them, you can add a powerful tool to your programming arsenal. Stacks can be used to solve a wide range of problems and can be especially useful in algorithmic problems and data processing tasks.

So go ahead and start experimenting with stacks in your own projects! With practice, you'll become a master of this powerful data structure in no time.

Further Reading

If you're interested in learning more about Python programming, check out some of our other blog posts on related topics:

  • Python Dictionary: Learn how to use Python's built-in dictionary data type, which allows you to store key-value pairs in a collection.

  • Python Functions: Functions are a core concept in Python programming. This blog post will teach you how to define and use functions in your own code.

  • Strings in Python: Strings are used to represent text in Python. In this post, you'll learn how to manipulate strings and perform common operations on them.

  • Python Loops: Loops are a fundamental programming concept that allow you to repeat a block of code multiple times. This post covers all the different types of loops in Python, including for loops, while loops, and nested loops.

By reading these blog posts, you'll deepen your knowledge of Python programming and be able to tackle more complex projects with confidence.

Top comments (0)