How To Build A Stack Class In Python

Photo by Iva Rajović on Unsplash

In this article we will be building a stack class in Python.

Even if you are unfamiliar with stacks or Python classes, below is everything you need to know to follow along!

Stacks are collections of objects arranged in a straight line, they follow a linear data structure in which adding or removing to and from the stack can only happen at a single end of the collection, making these LIFO or last in first out data structures. Think dinner plates, or a stack of pancakes.

We will be using a class to represent a stack in order to see it in action. We will write methods like push and pop which will add and remove objects from our collection.

To add items to the top of the stack we use:

append()

To retrieve an Item from the top if the stack we use:

pop()

Both these operations happen on the right side end of the collection.

Let’s jump into to it in Python!

We will start by writing our class and initializer also called a constructor, this constructor is essentially the template for our stack class out of which objects will be based on and created .

in Python we have the method __init__ as a constructor and we pass in self which refers to the specific instance of the class or the actual object:

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

Next we will created a method to check if our data is empty.

We could check and return whether or not our collection’s length is 0 with:

return lens(self.items) == 0

However an empty list returns false in python so we can simply use a logical not operator like this:

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

def is_empty(self):
return not self.items

Now let’s create a method for adding or pushing items into our list and it will take tow arguments; self and the item we are adding:

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

def is_empty(self):
return not self.items

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

In a similar way let’s add a remove or pop method:

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

def is_empty(self):
return not self.items

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

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

And this are array methods you are probably familiar with, here we are wrapping them in our stack class in order to control how we interface with the list.

Next we will add a method to find out the size of our stack and a method to peek as it were or print the last item in our list.

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

def is_empty(self):
return not self.items

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

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

And finally we will be adding an str that enables us to inspect and see the actual content of our stack with a print statement:

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

def is_empty(self):
return not self.items

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

def pop(self):
return self.items.pop()
def size(self):
return len(self.items)
def peek(self):
return self.items[-1]
def __str__(self):
return str(self.items)

This is the basics fo class definition and stack functionality written in Python.

Now if we wanted to create a stack we could do so like this:

items = Stack()

And we can call our methods:

print(s) 
[]
print(s.is_empty())
true
s.push("tomatoes")
["tomatoes"]
s.push("celery")
["tomatoes", "celery"]
s.pop()
["tomatoes"]

So to recap we created a Python stack class and wrote the constructor, which just initializes our items list. Then we wrote a method to add or push items to the top or end of the list, and a method to remove them from the top of the list.

We were able to check it’s size or length and we also wrote a method to check or peek what was at the top of our stack without actually removing from it as well as printing the entire stack content.

Congrats! you have implemented a stack class in Python.

Thank you for reading! and remember to follow for future articles where we will see how we can solve algorithmic problems via the use of a stack and other data structures.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store