Python Program to Implement a Stack


When it is required to implement a stack using Python, a stack class is created, and an instance of this class is created. Methods to push, pop elements are defined and the instance is used to call these methods.

Below is a demonstration of the same −

Example

 Live Demo

class Stack_struct:
   def __init__(self):
      self.items = []

   def check_empty(self):
      return self.items == []

   def add_elements(self, my_data):
      self.items.append(my_data)

   def delete_elements(self):
      return self.items.pop()

my_instance = Stack_struct()
while True:
   print('Push <value>')
   print('Pop')
   print('Quit')
   my_input = input('What operation would you like to perform ? ').split()

   my_op = my_input[0].strip().lower()
   if my_op == 'push':
      my_instance.add_elements(int(my_input[1]))
   elif my_op == 'pop':
      if my_instance.check_empty():
         print('The stack is empty')
      else:
         print('The deleted value is : ', my_instance.delete_elements())
   elif my_op == 'Quit':
      break

Output

Push <value>
Pop
Quit
What operation would you like to perform ? Push 6
Push <value>
Pop
Quit
What operation would you like to perform ? Psuh 8
Push <value>
Pop
Quit
What operation would you like to perform ? Psuh 34
Push <value>
Pop
Quit
What operation would you like to perform ? Pop
The deleted value is : 6
Push <value>
Pop
Quit

Explanation

  • The ‘Stack_struct’ class with required attributes is created.

  • It has an ‘init’ function that is used to create an empty list.

  • Another method named ‘check_empty’ that checks to see if a list is empty.

  • Another method named ‘add_elements’ is defined that adds elements to the empty list.

  • A method named ‘delete_elements’ is defined, that deletes elements from the list.

  • An object of the ‘Stack_struct’ class is created.

  • The user input is taken for the operation that needs to be performed.

  • Depending on the user’ choice, the operation is performed.

  • Relevant output is displayed on the console.

Updated on: 15-Apr-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements