All Courses

Python - Stacks

Neha Kumawat

2 years ago

python stacks | insideAIML
Table of Contents
  • Introduction
  • PUSH into a Stack
  • POP from a Stack

Introduction

            In the English dictionary, the word stack means arranging objects on over another. It is the same way memory is allocated in this data structure. It stores the data elements in a similar fashion as a bunch of plates are stored one above another in the kitchen. So stack data structure allows operations at one end which can be called the top of the stack. We can add elements or remove elements only form this en of the stack.
In a stack, the element inserted last in sequence will come out first as we can remove only from the top of the stack. Such a feature is known as Last in First Out(LIFO) feature. The operations of adding and removing the elements are known as PUSH and POP. In the following program, we implement it as add and remove functions. We declare an empty list and use the append() and pop() methods to add and remove the data elements.

PUSH into a Stack


class Stack:

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

    def add(self, dataval):
# Use list append method to add element
        if dataval not in self.stack:
            self.stack.append(dataval)
            return true
        else:
            return false
# Use peek to look at the top of the stack

    def peek(self):     
	    return self.stack[-1]

AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.peek()
print(AStack.peek())
AStack.add("Wed")
AStack.add("Thu")
print(AStack.peek())
When the above code is executed, it produces the following result:
Tue

Thu

POP from a Stack

            As we know we can remove only the topmost data element from the stack, we implement a python program that does that. The remove function in the following program returns the topmost element. we check the top element by calculating the size of the stack first and then use the in-built pop() method to find out the topmost element.
class Stack:

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

    def add(self, dataval):
# Use list append method to add element
        if dataval not in self.stack:
            self.stack.append(dataval)
            return true
        else:
            return false
        
# Use list pop method to remove element
    def remove(self):
        if len(self.stack) <= 0:
            return ("No element in the Stack")
        else:
            return self.stack.pop()

AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.add("Wed")
AStack.add("Thu")
print(AStack.remove())
print(AStack.remove())
When the above code is executed, it produces the following result:
Thu

Wed
I hope you enjoyed reading this article and finally, you came to know about Python - Stack.
   
For more such blogs/courses on data science, machine learning, artificial intelligence and emerging new technologies do visit us at InsideAIML.
Thanks for reading…
Happy Learning…

Submit Review