In computer science, think of a stack like a pile of plates. When you add a new plate, it goes on top of the pile, and when you take one off, you start from the top.
So, a stack has two main actions: you can add something to the top of the pile (like adding a plate), and you can take something off the top (like removing a plate).
This stack concept is handy for many computer tasks, like searching through data. This article will explain how to use stacks in Python, which is a programming language, to solve problems more easily.

Stack Implementation Planning
Before we dive into creating our stack, it’s essential to think about what we want it to do. Sure, we need it to have functions like adding items (.push()) and removing them (.pop()), but why stop there?
We might also want to know how many items are in our stack using Python’s len() function. It’s handy to have this because it helps us avoid issues when our stack is empty. Plus, having a way to peek at the top item without taking it off (.peek()) would be quite useful.
Now, let’s consider what happens when we try to peek or pop from an empty stack. We could return a special value like “NaN,” but that could lead to tricky problems later on, especially if we accidentally add NaN to our stack. Instead, it’s smarter to raise an exception when we try to peek or pop from an empty stack. This way, we catch the problem early during testing and can fix our code accordingly.
Let’s build the stack class
Here our stack is going to be a Python class. Once we declare our class, the first thing we want to add is a container to hold the items in our stack. To do this we create an internal variable:
class stack:
def __init__(self):
self.__index = []
When our stack class is initialized, it creates an empty list called __index to hold the stack items.
How to Set Up Len()Function –
First, let’s prepare the len() function. It’s crucial to check the length of our stack before we use other methods like .pop() and .peek(). To do this, we’ll utilize a special method in Python, known as the Dunder method, which allows us to customize the behavior of built-in operations. By implementing the len() Dunder method, we can define the “length” behavior required for our stack.
class stack:
def __init__(self):
self.__index = []
def __len__(self):
return len(self.__index)
Now, when we call len(stack_instance), it will return the number of items in our __index variable.
>>> s = stack()
>>> # some additional stack operations go here
>>> len(s) # fetch number of items in the stack
2
Now Let us See How To Set Up .push() method
Setting up the .push() method in Python is like adding an item to a stack. Imagine you have a stack of plates, and you want to add a new plate on top. Similarly, in Python, you create a method called .push() within a class representing your stack. This method takes the item you want to add as input and puts it on top of the stack.
Code Example:
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
print(f"Added {item} to the stack.")
# Creating a stack object
my_stack = Stack()
# Adding items to the stack
my_stack.push(5)
my_stack.push(10)
my_stack.push(15)
In this example, the .push() method adds items to the stack, similar to adding plates to a stack of dishes. When you call .push(5), it adds the number 5 to the stack, and so on.
Explanation:
- Defining the Stack Class:
- We start by defining a class named
Stack. This class will represent our stack data structure.
- We start by defining a class named
- Initializing the Stack:
- Inside the class, we define an
__init__method. This method is called the constructor and is executed when a new instance of the class is created. - Within the constructor, we initialize an instance variable
itemsas an empty list. This list will hold the elements of our stack.
- Inside the class, we define an
- Implementing the push Method:
- We define a method named
pushwithin theStackclass. This method takes two parameters:self(which represents the instance of the class) anditem(the element we want to add to the stack). - Inside the
pushmethod, we use theappend()function to add theitemto theitemslist. This effectively adds the item to the top of the stack. - Additionally, we print a message indicating that the item has been added to the stack.
- We define a method named
- Creating an Instance of the Stack:
- Outside the class definition, we create an instance of the
Stackclass namedmy_stack. This instance represents an actual stack object.
- Outside the class definition, we create an instance of the
- Adding Items to the Stack:
- We use the
pushmethod of themy_stackobject to add items to the stack. For example,my_stack.push(5)adds the number 5 to the stack,my_stack.push(10)adds 10, and so on.
- We use the
How To Set Up .peek() method
Setting up the .peek() method in Python is like peeking into a box to see what’s inside without actually taking anything out. Here’s how we do it:
- Define the
peekMethod in the Stack Class:- Inside our
Stackclass, we create a method calledpeek. This method doesn’t need any additional input other thanself, which represents the stack itself. - The purpose of the
peekmethod is to show us the item at the top of the stack without removing it.
- Inside our
- Implementing the
peekMethod:- Inside the
peekmethod, we check if the stack is not empty. If it’s empty, we print a message saying so. - If the stack is not empty, we use the index
-1to access the last item in theitemslist, which represents the top of the stack. - Finally, we return this item to the caller without removing it from the stack.
- Inside the
- Using the
.peek()Method:- After defining the
peekmethod in ourStackclass, we can create an instance of the stack, let’s call itmy_stack. - Now, whenever we want to see what’s on top of our stack, we simply call
my_stack.peek(). - For example, if our stack contains numbers
5,10, and15, callingmy_stack.peek()will show us15, the item at the top of the stack, without actually removing it.
- After defining the
In simple terms, setting up the .peek() method allows us to take a quick look at the top item in our stack without disturbing the rest of the items. It’s like peeking into the box to see what’s there, but keeping everything intact.
Code:
class Stack:
def __init__(self):
# Initialize an empty list to store stack items
self.items = []
def push(self, item):
# Add an item to the top of the stack
self.items.append(item)
def peek(self):
# Check if the stack is not empty
if not self.is_empty():
# Return the last item in the stack (top of the stack)
return self.items[-1]
else:
print("The stack is empty.")
def is_empty(self):
# Check if the stack is empty
return len(self.items) == 0
# Create an instance of the Stack class
my_stack = Stack()
# Push some items onto the stack
my_stack.push(5)
my_stack.push(10)
my_stack.push(15)
# Peek at the top item of the stack
print("Top item of the stack:", my_stack.peek()) # Output: 15
# Peek again after popping an item
my_stack.pop()
print("Top item of the stack after popping:", my_stack.peek()) # Output: 10
- We define a
Stackclass with methods to push items onto the stack, check if the stack is empty, and peek at the top item of the stack. - The
.peek()method allows us to see the top item of the stack without removing it. - We create an instance of the
Stackclass calledmy_stackand demonstrate how to use the.peek()method to peek at the top item of the stack.
Setting up the .pop() method
The .pop() method is exactly the same as the .peek() method with the further step of removing the returned item from the stack. Like .peek(), we’ll want to check for an empty list before trying to return a value:
class stack:
def __init__(self):
self.__index = []
def __len__(self):
return len(self.__index)
def push(self,item):
self.__index.insert(0,item)
def peek(self):
if len(self) == 0:
raise Exception("peek() called on empty stack.")
return self.__index[0]
def pop(self):
if len(self) == 0:
raise Exception("pop() called on empty stack.")
return self.__index.pop(0)
It’s important to note that a Python list has its own .pop() method, which behaves almost the same as our stack .pop() method, except that the list-version can take an index and “pop” an item from anywhere in the list.
Setting up the str() function
An additional thing we can do is tell Python how we want our stack printed with the str() function. At the moment, using it yields the following results:
>>> s = stack()
>>> print(str(s))
'<__main__.stack object at 0x000002296C8ED160>'
class stack:
def __init__(self):
self.__index = []
def __len__(self):
return len(self.__index)
def push(self,item):
self.__index.insert(0,item)
def peek(self):
if len(self) == 0:
raise Exception("peek() called on empty stack.")
return self.__index[0]
def pop(self):
if len(self) == 0:
raise Exception("pop() called on empty stack.")
return self.__index.pop(0)
def __str__(self):
return str(self.__index)
Using the stack class
We now have a usable stack class. The code below highlights all of the functionality we’ve implemented in our custom class:
>>> s = stack()
>>> s.peek() # stack = []
Exception: peek() called on empty stack.
>>> len(s)
0
>>> s.push(5) # stack = [5]
>>> s.peek()
5
>>> s.push('Apple') # stack = ['Apple',5]
>>> s.push({'A':'B'}) # stack = [{'A':'B'},'Apple',5]
>>> s.push(25) # stack = [25,{'A':'B'},'Apple',5]
>>> len(s)
4
>>> str(s)
"[25, {'A': 'B'}, 'Apple', 5]"
>>> s.pop() # stack = [{'A':'B'},'Apple',5]
25
>>> s.pop() # stack = ['Apple',5]
{'A': 'B'}
>>> str(s)
"['Apple', 5]"
>>> len(s)
2
In conclusion, we have successfully implemented the core functionalities of a stack class in Python, allowing us to manipulate data in a last-in-first-out (LIFO) manner. While our implementation is functional, there are several ways we could further enhance it to better suit our needs:
- Extending the .peek() Method: We could modify the
.peek()method to allow peeking at any item in the stack by specifying its index. This would provide more flexibility in accessing stack elements beyond just the top item. - Support for Appending Lists: Another improvement could involve supporting the appending of entire lists as a series of items within our stack. This feature would streamline the process of adding multiple items to the stack in one go, enhancing efficiency and convenience.
- Adding a .clear() Method: Introducing a
.clear()method would allow users to empty the stack, removing all items from it. This would be particularly useful in scenarios where the stack needs to be reset or cleaned up after processing. - Implementing Size Limit: Defining an upper limit to the stack size could be beneficial in real-world applications to prevent excessive memory consumption. By limiting the number of items that can be added to the stack, we can mitigate the risk of encountering memory-related issues such as “Out of Memory” exceptions.
By considering these enhancements and possibly implementing them, we can further refine our stack implementation and tailor it to better suit our specific requirements. With a solid foundation in place, we are poised to continue developing and expanding our stack implementation to meet the demands of various programming tasks and applications.





Leave a Reply