w3resource

Python Object-Oriented Programming: Stack class with push, pop, and display methods

Python OOP: Exercise-9 with Solution

Write a Python program to create a class representing a stack data structure. Include methods for pushing, popping and displaying 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:
            raise IndexError("Cannot pop from an empty stack.")

    # Check if the stack is empty
    def is_empty(self):
        return len(self.items) == 0

    # Display the items in the stack
    def display(self):
        print("Stack items:", self.items)

# Example usage
# Create an instance of the Stack class
stack = Stack()

# Push items onto the stack
stack.push(10)
stack.push(20)
stack.push(30)
stack.push(40)
stack.push(50)

# Display the items in the stack
stack.display()

# Pop items from the stack and print the popped items
popped_item = stack.pop()
print("Popped item:", popped_item)
popped_item = stack.pop()
print("Popped item:", popped_item)

# Display the updated items in the stack
stack.display()

Sample Output:

Stack items: [10, 20, 30, 40, 50]
Popped item: 50
Popped item: 40
Stack items: [10, 20, 30]

Explanation:

In this above exercise,

  • We define a Stack class 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 "display()" method simply prints the stack elements.
  • In the example usage section, we create an instance of the Stack class called stack. We push and pop several items onto the stack using the "push()" and "pop()" methods. We then display the stack elements using the "display()" method.

Flowchart:

Flowchart: Python - Stack class with push, pop, and display methods
Flowchart: Python - Stack class with push, pop, and display methods

Python Code Editor:

Previous: Shopping cart class with item management and total calculation.
Next: Queue class with enqueue and dequeue methods.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/oop/python-oop-exercise-9.php