Understanding the Stack Data Structure in Python

image of blog

What is a Stack?

A stack is a linear data structure that follows a particular order in which operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). Imagine a stack of books; the one you put on last is the first one you'll take off when you need it. That's exactly how a stack data structure works.

Basic Operations of Stack

A stack allows the following basic operations:

  • Push: Add an item to the stack. If the stack is full, then it is said to be an Overflow condition.

  • Pop: Remove an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, it is said to be an Underflow condition.

  • Peek or Top: Return the top element of the stack.

  • isEmpty: Check if the stack is empty.

Implementing a Stack in Python

Python doesn’t have a built-in stack data structure, but it can be easily implemented using a list. Let’s look at a simple implementation:

class Stack:
    """
    Stack Implementation in Python
    """    def __init__(self):
        """
        Initialize an empty stack
        """        self.items = []

    def push(self, item):
        """
        Add an item to the top of the stack
        """        self.items.append(item)

    def pop(self):
        """
        Remove the item from the top of the stack
        """        if not self.is_empty():
            return self.items.pop()
        else:
            return 'Stack is empty'    def is_empty(self):
        """
        Check if the stack is empty
        """        return len(self.items) == 0    def get_stack(self):
        """
        Get all the items in the stack
        """        return self.items

    def peek(self):
        """
        Get the top item of the stack
        """        if not self.is_empty():
            return self.items[-1]
        else:
            return 'Stack is empty'

In the above code, self.items is a Python list that is used to store stack elements. The push method appends a new element to the end of the list, which is equivalent to the stack's top. The pop method removes the last item from the list, effectively removing the top item of the stack. The peek method simply returns the last element without removing it, allowing us to see what’s at the top without modifying the stack.

Example Usage

if __name__=='__main__':
    stack = Stack()
    stack.push('A')
    stack.push('B')
    print(stack.pop())      # Output: B
    stack.push('C')
    print(stack.peek())     # Output: C
    print(stack.get_stack())  # Output: ['A', 'C']
Output:
B
C
['A', 'C']

This simple example demonstrates pushing and popping items to and from the stack. As expected, the pop operation returns 'B', which is the last element we pushed, and the peek operation shows 'C', which is now at the top of the stack.

Conclusion

Stacks are a vital data structure for many applications, such as undo mechanisms in text editors, function call stacks in programming languages, and for evaluating expressions in calculators. The ease of implementation in Python makes it an excellent language for experimenting with and understanding this fundamental concept .Understanding how to implement a stack is just the beginning. As we grow more comfortable with stacks, wecan explore more complex uses, such as reversing strings, parsing expressions, and even navigating mazes.

Please visit the github repo for entire code. Thank You

niranjanblank

https://github.com/niranjanblank/Data_Structures/tree/master/Stack