PYTHON
Basic Stack Implementation Using Python Lists
Understand how to implement a Last-In, First-Out (LIFO) stack data structure using Python's built-in list operations for push and pop.
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()
else:
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]
else:
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)
# 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 empty? {my_stack.is_empty()}")
my_stack.pop()
print(f"Stack empty? {my_stack.is_empty()}")
# my_stack.pop() # This would raise an error
How it works: This snippet shows a straightforward implementation of a stack using a standard Python list. The `append()` method is used for `push` operations (adding elements to the top), and the `pop()` method (without an index) efficiently removes and returns the last element, adhering to the Last-In, First-Out (LIFO) principle. It also includes methods for peeking, checking emptiness, and size.