DEV Community


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):
    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
print("Stack is Empty:",s.is_empty())
print("Stack after appending =",s.get_stack())
print("Stack after removing elements =",s.get_stack())
print("Peek element =",s.peek())
Enter fullscreen mode Exit fullscreen mode


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)

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.

One does not simply learn git