Skip to Content

Python – Check If Set Is Empty – With Examples

In this tutorial, we will look at how to check if a set is empty or not in Python with the help of some examples.

check if a set is empty in python

A set is said to be empty if it does not contain any elements. You can use the following methods to check if a set is empty or not in Python.

  • Comparing the length of the set with zero.
  • Comparing the set with an empty set.
  • Using the set in a boolean context.

Let’s now take a look at each of the above methods with the help of some examples.

The length of an empty set is zero.

You can use the Python len() function to calculate the length of the set and then compare it with zero to check if the set is empty or not. Here’s an example –

# create two sets - s1 is empty and s2 is non-empty
s1 = set()
s2 = {1, 2, 3}
# check if set is empty
print(len(s1)==0)
print(len(s2)==0)

Output:

True
False

We get True as the output for the set s1 as it is empty and False for the set s2 because it’s not empty (has non-zero length).

You can also check if a set is empty or not by comparing it with an empty set using the == operator. Let’s look at an example.

# create two sets - s1 is empty and s2 is non-empty
s1 = set()
s2 = {1, 2, 3}
# check if set is empty
print(s1 == set())
print(s2 == set())

Output:

True
False

We get the same results as above.

Note that using curly braces without any elements, {} represents an empty dictionary and not an empty set. Thus, we’re using set() to represent an empty set.

If you use a set in a boolean context, it will evaluate to True if it has any elements and it will evaluate to False if the set is empty. Thus, you can use the expression not s to check if the set s is empty or not.

Here’s an example.

# create two sets - s1 is empty and s2 is non-empty
s1 = set()
s2 = {1, 2, 3}
# check if set is empty
print(not s1)
print(not s2)

Output:

True
False

We get the same result as above. True for the set s1 as it’s empty and False for the set s2 as it’s not empty (s2 has three elements).

In this tutorial, we looked at three methods to check if a set is empty or not. Use the method that you are the most comfortable with. Using the len() function to check if a set is empty may be more explicit but it’s very intuitive and is consistent with the mathematical definition of an empty set.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush

    Piyush is a data scientist passionate about using data to understand things better and make informed decisions. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.