Stack Implementation in Python
Welcome to the Stack Implementation with Python Page!
As we all know Python consists of many data structures like lists, tuples, arrays, and dictionaries. But we must know the basic data structures used in problem-solving which you will go through in this blog.
Stack is one of the basic data structures. The stack implementation goes like this:
'''
_______
|___1___| STACK with 1 element
_______
|___2___| PUSH(2) : Element is pushed to the top of the
|___1___| stack
_______
|___1___| POP() : Removes the top element
peek() : returns element at top
isEmpty() : checks if stack is empty
'''
class Stack:
def __init__(self, stack):
self.stack = stack
def push(self, ele):
self.stack.append(ele)
def pop(self):
if self.stack :
self.stack.pop()
else:
print("Stack is empty")
Explanation
Check out the example I have demonstrated in the above code.
A stack is just like a stack of books. The book at the top is always removed from the stack of books. In the same sense, an element is popped from the top of the stack.
The book is stacked on top of another book. In the same way, the element is always pushed on top of the stack.
We initialize the stack class using a list and perform the push and pop operations using append() and pop() functions.
Stack stores data in the FILO method i.e. First-In-Last-Out method which means the element inserted first will be popped at last.
append(): This method appends an element to the list
pop(): This method removes the last item in the list which means the element which is recently inserted.
This was the Stack Implementation using Python. I hope you found this useful and informative. If there are any doubts then please let me know.
HAPPY CODING!
Subscribe to my newsletter
Read articles from Jai Irkal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Jai Irkal
Jai Irkal
Hello developers! I am Jai Irkal studying in 3rd Year CSE at SDM College of Engineering and Technology, Dharwad. I am crazy about Flutter App Development. I love Java and Python Programming. Currently learning Web Development.