DEV Community

Jai Irkal
Jai Irkal

Posted on

Stack Implementation Using Python

How stack works and logic

If we imagine a stack horizontally then...
Element in stack is inserted in the same way we append an element to an array. So this logic could be used for the push function of our stack.
Element is popped from the end of the stack so we have a direct pop() function which can be implemented in the pop function for this. pop() removes the first element from a list so we use pop(-1) to remove the last element.

This was a question from GeeksForGeeks Practice

Ex: push(1), push(2), push(3), pop()
[1] [1,2] [1,2,3] [1,2]

Code

`class MyStack:

def __init__(self):
    self.arr=[]

#Function to push an integer into the stack.
def push(self,data):
    #add code here
    self.arr.append(data)

#Function to remove an item from top of the stack.
def pop(self):
    #add code here
    if len(self.arr) > 0:
        popped = self.arr.pop(-1)
        return popped
    else:
        return -1`
Enter fullscreen mode Exit fullscreen mode

Thank You. Hope you liked this solution. If there are better solutions or you have your own different solution then comment it below👍

Top comments (0)