PYTHON

Implement a Last-In, First-Out (LIFO) Stack with Python Lists

Learn to implement a basic stack data structure in Python using a list, demonstrating push, pop, and peek operations for managing data in a LIFO manner.

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."""
        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."""
        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()
my_stack.push('Task 1')
my_stack.push('Task 2')
my_stack.push('Task 3')

print(f"Stack after pushes: {my_stack}") # Expected: ['Task 1', 'Task 2', 'Task 3']
print(f"Top item (peek): {my_stack.peek()}") # Expected: Task 3
print(f"Popped item: {my_stack.pop()}")    # Expected: Task 3
print(f"Stack after pop: {my_stack}")    # Expected: ['Task 1', 'Task 2']
print(f"Is stack empty? {my_stack.is_empty()}") # Expected: False
my_stack.pop()
my_stack.pop()
print(f"Is stack empty? {my_stack.is_empty()}") # Expected: True
How it works: This snippet demonstrates how to build a basic Last-In, First-Out (LIFO) stack using Python's built-in list. The `push` method uses `append()` to add elements to the end of the list (top of the stack). The `pop` method uses `pop()` to remove and return the last element, mimicking LIFO behavior. `peek` allows viewing the top element without removal, and `is_empty` checks the stack's status. This simple implementation is efficient for most basic stack needs.

Need help integrating this into your project?

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

Hire DigitalCodeLabs