Python data structure stack using list

Python data structure stack using list is one of the topics of CBSE Class 12 Computer science subject. In this article we will discuss about it. So let’s begin!!!

Introduction to Python data structure stack

As data structure is very important aspect of any programming language so is python too.

A data structure is a way of store, organize, or manage data in efficient and productive manner.

The python data structure stack is a linear data structure. It follows the principle of LIFO (Last In First Out). The representation of data is something like this:

python data structure stack
An example of python data structure stack

By observing above image you can understand the following:

  1. The data can be inserted or deleted from the top only
  2. Elements can be inserted or deleted any time
  3. The insert operation is known as push
  4. The delete operation is known as pop
  5. When the top element is inspected, it is known as peek or inspection
  6. When we have a fixed-length list and we are trying to push an element in a list, it raises one error that is known as overflow
  7. When the list is empty and we are trying to pop an element, it will raise an error that is known as underflow

Implementation of stack using a list

To implement python data structure stack create a menu driven program followed by the functions for push, pop, peek, display and empty.


Create a menu driven program

I have created a function named main_menu() as following:

 s=[] # An empty list to store stack elements, initially its empty
 top = None # This is top pointer for push and pop operation
def main_menu():
    while True:
        print("Stack Implementation")
        print("1 - Push")
        print("2 - Pop")
        print("3 - Peek")
        print("4 - Display")
        print("5 - Exit")
        ch = int(input("Enter the your choice:"))
        if ch==1:
            #push function calling
        elif ch==2:
            #pop function calling
        elif ch==3:
            #peek function calling
        elif ch==4:
            #display function calling
        elif ch==5:
            print("Sorry, You have entered invalid option")

Checking stack underflow

To check the stack is empty or not write a function. Here I have written a function named check_stack_isEmpty(stk).

def check_stack_isEmpty(stk):
    if stk==[]:
        return True
        return False

Push function

A function to push an element. To push the element append() method is used as well as the position of the top should be changed. Observe the following code:

def push(stk,e):
    top = len(stk)-1

Call this function in main_menu() function when ch = 1. Observe this code:

ele=int(input("Enter the value to push an element:"))

Display function

Write a function to check the element is inserted or not, observe this code:

def display(stk):
    if check_stack_isEmpty(stk):
        print("Stack is Empty")
        top = len(stk)-1
        for i in range(top-1,-1,-1):

Calling display in main_menu() function:


Pop Function

The pop function requires a validation to check whether stack is underflow or not, if it is not then use the logic for delete element from top. Have a look at this code:

def pop_stack(stk):
    if check_stack_isEmpty(stk):
        return "UnderFlow"
        e = stk.pop()
        if len(stk)==0:
            top = None
            top = len(stk)-1
        return e

Function call code in main_menu:

           if e=="UnderFlow":
               print("Stack is underflow!")
               print("Element popped:",e)

Peek Function

The code is similar like pop, instead of popping element just write statement to display the value. Observe this code:

def peek(stk):
    if check_stack_isEmpty(stk):
        return "UnderFlow"
        top = len(stk)-1
        return stk[top]

Function call code in main_menu() function:

if e=="UnderFlow":
print("Stack is underflow!")
print("The element on top is:",e)

Download the complete program .py file

Thank you for reading this article. Now implement this by yourself and enjoy the learning!!

Share this article with your friends and circle. Comment your views, feedback or any doubt in comment section. See in next article, till then keep reading, keep sharing!!!!

Comment Your Views

%d bloggers like this: