Implementing Stacks in Python

What is a Stack?

A stack is a collection, meaning that it is a data structure that contains multiple elements. Here adding(push) and removal(pop) of data always affect one end of the stack. This end is usually referred as “Top”. Other end is usually referred as “Base”. It’s a “Last In, First Out” (LIFO) data structure. Which means last data added to the stack is removed first.

Stack Operations

  • Stack() – Create a stack
  • isEmpty() – Check whether the stack is empty. Returns “True” if the stack is empty if not returns “False”
  • size() – Return the size of the stack ie number of data items in the stack
  • push() – Add data to the stack (Remember data is always added to the “Top”)
  • pop() – Remove the top-most element from the stack and return it
  • peek() – Return the top-most element (without removing)

Defining a Stack in Python Using Lists

class Stack:
    def __init__(self):
        self.items = [] #create new list with no items

    def __repr__(self):
        return repr(self.items) #define what to return is the stackname is called

    def isEmpty(self):
        return self.items == [] #check whether list if empty and retuen T or F

    def size(self):
        return len(self.items) #retun size of stack (= length of list)

    def push(self,val):
        self.items.append(val) #add the argument pass to the end of list

    def pop(self):
        return self.items.pop() #return the last item in list because index not specified

    def peek(self):
        return self.items[-1] #return last item (-1 because from right indices are negative)

 Definitions Explained

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

This code will create an empty list when the Stack() is called.

def __repr__(self):
        return repr(self.items)

This will tell Python what to return when a stack made with this class is called. For example if you create a list using python lists you can print it to see what is inside the list. Here this code will tell Python to return what’s inside the stack . So if you print a stack ( print (<stack_name>)) you can see what is in it.

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

When the isEmpty() method is called , this will check if the stack is equal to a empty list ie [ ] .(Because stack is defined using lists we compare the stack with an empty list )

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

Here we use the method len() to return the length of the list used in stack. Here length of the list is equal to the number of items in the stack

def push(self,val):

Push will add data to the “Top” of the stack. Here we append the item passed when calling this method to the list. (Appending will always add items to the back of the list)

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

This will remove and return the top-most item of the stack. That means it will return the last item of the list used as the stack. Note that here we don’t specify which item to pop so Python will automatically pop the last item from the list

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

Peek will return the top-most element in the stack without removing it. When we consider a list we can use negative index to represent items from the back of the list. Therefore when we use -1 as the index it will return the last item (This is the top-most item of the stack)



The owner of [] will not be liable for any errors or omissions in this information nor for the availability of this information. The owner will not be liable for any losses, injuries, or damages from the display or use of this information.
This terms and conditions are subject to change at anytime with or without notice.


Proud UCSCian | Proud Devan | Computer Geek | Superman | Love Chess & Programming

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.