PYTHON

Implement a Basic Stack (LIFO) with Python Lists

Understand how to implement a Last-In, First-Out (LIFO) stack data structure using Python's built-in list methods like append() and pop(), crucial for managing sequential data.

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

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

    def pop(self):
        """Removes and returns the item from the top of the stack.
        Raises an IndexError if the stack is empty."""
        if not self.is_empty():
            return self._items.pop()
        raise IndexError("pop from empty stack")

    def peek(self):
        """Returns the item at the top of the stack without removing it.
        Raises an IndexError if the stack is empty."""
        if not self.is_empty():
            return self._items[-1]
        raise IndexError("peek from empty stack")

    def is_empty(self):
        """Checks if the stack is empty."""
        return len(self._items) == 0

    def size(self):
        """Returns the number of items in the stack."""
        return len(self._items)

    def __str__(self):
        return str(self._items)

# Example Usage:
my_stack = Stack()
print(f"Is stack empty? {my_stack.is_empty()}") # True

my_stack.push(10)
my_stack.push(20)
my_stack.push(30)
print(f"Stack after pushes: {my_stack}") # [10, 20, 30]
print(f"Stack size: {my_stack.size()}") # 3

print(f"Top element (peek): {my_stack.peek()}") # 30
print(f"Popped element: {my_stack.pop()}") # 30
print(f"Stack after pop: {my_stack}") # [10, 20]

print(f"Popped element: {my_stack.pop()}") # 20
print(f"Stack after pop: {my_stack}") # [10]

print(f"Is stack empty? {my_stack.is_empty()}") # False
How it works: This Python snippet demonstrates a simple implementation of a Stack, a Last-In, First-Out (LIFO) data structure, using a standard Python list. The `push()` operation uses `append()` to add items to the end of the list, and `pop()` removes items from the end, effectively simulating the LIFO behavior. Methods like `peek()`, `is_empty()`, and `size()` provide common stack functionalities, with error handling for operations on an empty stack.

Need help integrating this into your project?

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

Hire DigitalCodeLabs