Stack in Python

By Gaurav Jain on March 3, 2018

Implementing a Stack datastructure using Python

A stack is a datastructure with two basic operations, those are push and pop.

  • Push: Add items in the stack from top e.g putting books on top of other books
  • Pop: Remove items from the top in the stack and return the removed item e.g removing top book to get the second top book

Apart from these two necessary operations, There are few other useful actions as well.

  • Peek: It’s similar to Pop operations but it doesnt remove the item, it just return the value
  • is_empty: to check if stack is empty or has at least 1 item in it. return True if empty, False otherwise
  • size: to get the current size(how many items are in the stack at the moment)
class Stack:

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

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

    def pop(self):
        if self.is_empty():
            return "Stack Is Empty"
        return self.stack.pop()

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

    def is_empty(self):
        return len(self.stack) == 0

    def size(self):
        return len(self.stack)

Usage:

>>> s = Stack()
>>> s.is_empty()
True
>>> s.size()
0
>>> s.push('cat')
>>> s.push('dog')
>>> s.push('cow')
>>> s.is_empty()
False
>>> s.size()
3
>>> s.peek()
'cow'
>>> s.pop()
'cow'
>>> s.pop()
'dog'
>>> s.size()
1
>>> s.peek()
'cat'

This will create a stack of unlimited size/capacity (i.e we can store as many items as we want). in real world scenario we have limited size which I’ll discuss in this post.

This code can be found on github [Python-DSA] repository.

If you find anything wrong or has a better solution, please feel free to create issues on this repo.