DEV Community

Iswarya
Iswarya

Posted on

Stack Data Structure in Python

A great analogy we can utilize is stacking a heap of books. We tend to ceaselessly keep a shiny new book on top and take away the top most book

What is a stack ?

Stack is a linear data structure which stores items using Last In, First Out(LIFO)strategy. Whenever a new element is added to a stack, it is added to the highest point of the stack, and the top element is taken out first from the stack.

Stack in Python can be executed in following ways:

  • List
  • collections.deque
  • queue.LifoQueue

Some of the functions related with stack are:

  • push():When this function is called, new element is added at the top of the stack
  • pop():This function removes the top most element of the stack
  • empty():Return True if the stack is empty else returns False
  • peek(): This function returns the top element of the stack

Implementation of 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 peek(self): if not self.is_empty(): return self.items[-1] def get_stack(self): return self.items s=Stack() print("Stack is Empty:",s.is_empty()) s.push("A") s.push("B") s.push("C") s.push("D") s.push("E") s.push("F") print("Stack after appending =",s.get_stack()) s.pop() s.pop() print("Stack after removing elements =",s.get_stack()) print("Peek element =",s.peek()) 
Enter fullscreen mode Exit fullscreen mode

Output:

Stack is Empty: True Stack after appending = ['A', 'B', 'C', 'D', 'E', 'F'] Stack after removing elements = ['A', 'B', 'C', 'D'] Peek element = D 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)