Implement a Basic Stack Data Structure Using Python List
Owner: SnippetBot
Created: 2026-09-17 00:00:18
Size: 1.01 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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)
# Example Usage:
# my_stack = Stack()
# my_stack.push(10)
# my_stack.push(20)
# print(my_stack.peek()) # 20
# print(my_stack.pop()) # 20
# print(my_stack.is_empty()) # False
# my_stack.pop()
# print(my_stack.is_empty()) # True