Sitemap

Checking if a Stack is Empty | Python

2 min readApr 6, 2023

--

Problem

Write a function to check if a stack is empty or not. A stack is said to be empty if there are no elements in it.

Press enter or click to view image in full size
Photo by Holly Stratton on Unsplash

Example

Suppose we have a stack s containing the following elements:

s = [5, 10, 15]

We want to check if the stack is empty or not. Since s contains elements, the function should return False.

Get Saurabh Mishra’s stories in your inbox

Join Medium for free to get updates from this writer.

On the other hand, if we have an empty stack s:

s = []

The function should return True.

Solution

To check if a stack is empty, we can simply check if the length of the stack is zero or not. If the length of the stack is zero, it means that there are no elements in the stack, and therefore the stack is empty.

Here’s the Python code to implement the function using the list data structure:

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

We can then use this function to check if a stack is empty or not. For example:

s = [5, 10, 15]
if is_empty(s):
print("The stack is empty")
else:
print("The stack is not empty")
The stack is not empty
s = []
if is_empty(s):
print("The stack is empty")
else:
print("The stack is not empty")
The stack is empty

--

--

Saurabh Mishra
Saurabh Mishra

Written by Saurabh Mishra

Full Stack Developer || Founder@LearnNGrowIt