DSA Stacks
Language: Data Structures
class Stack:
def __init__(self):
self._items = []
def push(self, value):
self._items.append(value)
def pop(self):
if self.is_empty():
raise IndexError("pop from an empty stack")
return self._items.pop()
def peek(self):
if self.is_empty():
raise IndexError("peek at an empty stack")
return self._items[-1]
def is_empty(self):
return len(self._items) == 0
def size(self):
return len(self._items)
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop()) # 3
print(stack.peek()) # 2
print(stack.size()) # 2Output
Click Run to execute this code.