Data Structures

How do you implement a stack in Python?

Medium
5
Added
A stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle. You can implement a stack using a list in Python.

Solution Code

Data Structures
class Stack:
    def __init__(self):
        self.items = []

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

    def pop(self):
        if not self.is_empty():
            return self.items.pop()
        return None

    def is_empty(self):
        return len(self.items) == 0

# Example usage
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop())
Explanation
This code snippet demonstrates how to implement a stack in Python.

Guided Hints

Define a Stack class
Implement push and pop methods
Use a list to store stack items