Data Structure in Python: Stack

Shaswat Singh
2 min readMar 20, 2020

--

Hello everyone, this is the series I has started on a different data structure which primarily tries to find different implementation or example in that particular data structure.

In this blog, our focus is mostly based on how that implement the data structure in python.

So let’s talk about stack and I am going only in this blog as it should be repetitive for the next blog.

Some representation of stacks like a stack of block and stack of plate

In which if we want to add(push) something or remove(pop) something we always do from the top of the stack that is why it is called LIFO(Last In First Out) data structure because the last element remove first.

Major Operation used in stack:

  1. Push: Add an element to the stack
  2. Pop: Remove element from the stack
  3. check for empty: Check where the stack is empty or not
  4. Give the top element: Returns the top element of the stack

Implementation of stack using list in python

# create a class Stack

class Stack():
def __init__(self):
self.items = []

def push(self,item):
self.items.append(item)

def pop(self):
return self.items.pop()

def is_empty(self):
return self.items == []

def get_top(self):
if not self.is_empty():
return self.items[-1]


def get_stack(self):
return self.items


s = Stack() # make a stack object
s.push("A") # adding "A" to stack
s.push("B") # adding "B" to stack
print(get_stack) # print the current stack
s.pop() # removing the top or last element of stack
s.push("C") # adding "A" to stack
print(get_stack) # print the current stack
print(s.is_empty()) # check whether the stack is empty or not
print(s.get_top()) # getting the top of stack
s.pop() # removing the top or last element of stack
s.pop() # removing the top or last element of stack
print(s.is_empty()) # check whether the stack is empty or not

The output should be:

["A","B"]
["A","C"]
False
C
True

And if you are reading this then thank you were much for that and please leave a comment if you want some changes or improvisation.

We will meet in the next post with whether the parenthesis is balanced or not.

PEACE

--

--