Python Object-Oriented Programming: Stack class with push and pop methods
Write a Python program to create a class representing a stack data structure. Include methods for pushing and popping elements.
Sample Solution:
Python Code:
# Define a class called Stack to implement a stack data structure
class Stack:
# Initialize the stack with an empty list to store items
def __init__(self):
self.items = []
# Push an item onto the stack
def push(self, item):
self.items.append(item)
# Pop (remove and return) an item from the stack if the stack is not empty
def pop(self):
if not self.is_empty():
return self.items.pop()
else:
return "Cannot pop from an empty stack."
# Check if the stack is empty
def is_empty(self):
return len(self.items) == 0
# Get the number of items in the stack
def size(self):
return len(self.items)
# Peek at the top item of the stack without removing it, if the stack is not empty
def peek(self):
if not self.is_empty():
return self.items[-1]
else:
return "Empty stack."
# Example usage
# Create an instance of the Stack class
stack = Stack()
# Push items onto the stack
stack.push(0)
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
# Print the size of the stack and the top element
print("Stack size:", stack.size())
print("Top element:", stack.peek())
# Pop an item from the stack, and print the popped item, and the updated size and top element
popped_item = stack.pop()
print("\nPopped item:", popped_item)
print("\nStack size:", stack.size())
print("Top element:", stack.peek())
#----------------------------------------
# Create another instance of the Stack class
stack1 = Stack()
# Print the size of the empty stack and attempt to pop an item (with an error message)
print("\nStack size:", stack1.size())
popped_item = stack1.pop()
print("\nPopped item:", popped_item)
Sample Output:
Stack size: 5 Top element: 4 Popped item: 4 Stack size: 4 Top element: 3 Stack size: 0 Popped item: Cannot pop from an empty stack.
Explanation:
In this above exercise,
- We define a class "Stack" representing a stack data structure. It has an attribute called items, which is initially an empty list.
- The "push()" method takes an item as an argument and appends it to the items list, effectively adding it to the top of the stack.
- The "pop()" method removes and returns the topmost item from the stack. It checks if the stack is empty before popping an item. If the stack is empty, it raises an IndexError with an appropriate error message.
- The "is_empty()" method checks if the stack is empty by examining the length of the items list.
- The "size()" method returns the number of items currently in the stack by returning the length of the items list.
- The "peek()" method returns the topmost item from the stack without removing it. It checks if the stack is empty before peeking into it. If the stack is empty, it raises an IndexError with an appropriate error message.
- In the example usage section, we create an instance of the Stack class called stack. We push several items onto the stack using the push method. We then demonstrate how to access the stack size using the size method and peek at the topmost element with the "peek()" method.
- We also demonstrate popping an item from the stack using the "pop()" method.
Flowchart:
Python Code Editor:
Previous: Binary search tree class with insertion and search methods.
Next: Linked list class with insertion, deletion, and display methods.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics