Create A Stack Using Array in Python

Typically when solving programming questions, sometimes when the brain is clustered with multiple thoughts. Even the simplest fundamentals of programming seem very difficult to apply while solving a question. So having a strong grip on the fundamentals of programming mostly automates the thought process for applying these concepts while writing up a code. Stack is one of the most basic data structures you must know. Therefore in today’s article, we’ll learn how to create a stack using Array in Python.


So open up your IDE and let’s get started real quick. Once you understand the logic practice this program on your own to make your brain work in a problem-solving way. This is a pretty easy question so you might not get asked in an interview but practising this question will make your grip more firm in the Python language.


What’s The Approach?


  • We will create an array.


  • If there’s no element in the array, we will return -infinite also the stack will be called underflow.


  • The element added at the last will be removed first if we want to delete elements from the stack.


  • push() method will be used to insert the elements in the stack, the pop() method will be used to remove an element from the stack.


Also Read: How To Install Python on Windows 11


Python Program To Create A Stack Using Array



push(stack, str(5))

push(stack, str(10))

push(stack, str(15))





5 pushed to stack 

10 pushed to stack 

15 pushed to stack 

15 popped from stack


# Python program for implementation of stack

# import maxsize from sys module
# Used to return -infinite when stack is empty
from sys import maxsize

# Function to create a stack. It initializes size of stack as 0
def createStack():
    stack = []
    return stack

# Stack is empty when stack size is 0
def isEmpty(stack):
    return len(stack) == 0

# Function to add an item to stack. It increases size by 1
def push(stack, item):
    print(item + " pushed to stack ")
# Function to remove an item from stack. It decreases size by 1
def pop(stack):
    if (isEmpty(stack)):
        return str(-maxsize -1) # return minus infinite
    return stack.pop()

# Function to return the top from stack without removing it
def peek(stack):
    if (isEmpty(stack)):
        return str(-maxsize -1) # return minus infinite
    return stack[len(stack) - 1]

# Driver program to test above functions
stack = createStack()
push(stack, str(5))
push(stack, str(10))
push(stack, str(15))
print(pop(stack) + " popped from stack")



I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

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