How to implement a simple Stack data structure in Python

In this Python tutorial, we will learn how to implement a stack data structure in Python language. First, what is stack? A simple data structure which allows the adding and removing elements in a particular order. It can also define as a data type with a bounded capacity.

 

Features of stack:

  • In stack two modules are present. Those are push and pop().
  • push() module used to add elements in the stack. The pop() module used to remove elements in the stack.
  • Both push() and pop() are useful only at the top of the stack. That means a new element will be added at the top of stack using push() module and an the top element will be deleted using pop() module.

 

                     Implementation of Stack in Python

Source Code: Stack in Python

stack = []  # initialize this list as a stack

print('\nCurrent Stack :', stack)

# print('\nPush items into the Stack')

n = int(input('Enter the number of elements in Stack?\t '))

# add items to the stack
for i in range(n):
    # push items into stack
    
    b=int(input('Enter the element to be pushed\t'))
    
    stack.append(b)
    print('Current Stack :', stack,'\tStack Size :', len(stack))

print('\nPop items from the stack')
# now pop items from the stack
while len(stack) > 0:  # checking if stack is empty
    stack.pop()
    print('Current Stack :', stack, '\tStack Size :', len(stack))

if len(stack)==0:
    print('Empty Stack')

First, create an empty stack. If the stack is empty, it displays as an empty stack. Since the stack is empty the program asks how many elements to enter into the stack. The stack displays current size and no. of elements for each iteration.

Output:-

Current Stack : []
Enter the number of elements in Stack? 3
Enter the element to be pushed 1
Current Stack : [1] Stack Size : 1
Enter the element to be pushed 4
Current Stack : [1, 4] Stack Size : 2
Enter the element to be pushed 6
Current Stack : [1, 4, 6] Stack Size : 3

Pop items from the stack
Current Stack : [1, 4] Stack Size : 2
Current Stack : [1] Stack Size : 1
Current Stack : [] Stack Size : 0
Empty Stack

 



You can also read,

What are the Mutable and Immutable objects in Python?

Compute Eigen Values Vectors in Python

 

Leave a Reply

Your email address will not be published. Required fields are marked *