PYTHON

Implement a LIFO Stack Using Python Lists

Understand how to implement a Last-In, First-Out (LIFO) stack data structure in Python using simple list operations like append and pop, essential for many algorithms.

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

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

    def push(self, item):
        self._items.append(item)  # Add to the end of the list

    def pop(self):
        if self.is_empty():
            raise IndexError("pop from empty stack")
        return self._items.pop()  # Remove from the end of the list

    def peek(self):
        if self.is_empty():
            raise IndexError("peek from empty stack")
        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()}") # Output: 2
print(f"Top element: {my_stack.peek()}") # Output: 20
print(f"Popped: {my_stack.pop()}")    # Output: 20
print(f"Stack size after pop: {my_stack.size()}") # Output: 1
my_stack.push(30)
print(f"Popped: {my_stack.pop()}")    # Output: 30
print(f"Is stack empty? {my_stack.is_empty()}") # Output: False
print(f"Popped: {my_stack.pop()}")    # Output: 10
print(f"Is stack empty? {my_stack.is_empty()}") # Output: True
How it works: This snippet demonstrates implementing a Last-In, First-Out (LIFO) stack using a standard Python list. The `push` operation uses `append()` to add elements to the end of the list, and `pop` uses the list's `pop()` method (without an index) to remove and return the last element added. This natural behavior of Python lists makes them suitable for efficient stack implementations, as adding/removing from the end of a list is an O(1) operation.

Need help integrating this into your project?

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

Hire DigitalCodeLabs