← Back to all snippets
PYTHON

Simple Stack Implementation Using Python Lists

Learn to implement a Last-In, First-Out (LIFO) stack data structure using Python's built-in list, perfect for managing function calls or undo operations.

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

    def is_empty(self):
        return not bool(self._items)

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

    def pop(self):
        if self.is_empty():
            raise IndexError("Stack is empty")
        return self._items.pop()

    def peek(self):
        if self.is_empty():
            raise IndexError("Stack is empty")
        return self._items[-1]

    def size(self):
        return len(self._items)

# Example Usage
my_stack = Stack()
my_stack.push(10)
my_stack.push(20)
print(f"Stack size: {my_stack.size()}")
print(f"Top element: {my_stack.peek()}")
print(f"Popped element: {my_stack.pop()}")
print(f"Stack size after pop: {my_stack.size()}")
How it works: This snippet demonstrates how to implement a basic stack using a Python list. The `push` method adds elements to the end of the list (top of the stack), and the `pop` method removes elements from the end, following the Last-In, First-Out (LIFO) principle. `peek` allows viewing the top element without removing it, `is_empty` checks if the stack has elements, and `size` returns the number of elements.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs