Python – Check if Set is Empty

Python – Check if Set is Empty

There are many ways in which you can check if a given set is empty in Python.

1. Checking if Set is empty using NOT operator and Set

To check if a given set is empty in Python, you can use the set object with NOT operator as a condition in an if or if else statement.

For example, consider the following condition.

not set_1

The above condition returns True if the set set_1 is empty, or returns False if the set is not empty.

Let us write an example program, where we take a set in set_1, and check if the set is empty.

Python Program

set_1 = set()

if not set_1:
    print("The set is EMPTY.")
else:
    print("The set is NOT EMPTY.")
Run Code Copy

Output

The set is EMPTY.

Now, let us take a non-empty set in set_1, and run the program.

Python Program

set_1 = set({"apple", "banana", "cherry"})

if not set_1:
    print("The set is EMPTY.")
else:
    print("The set is NOT EMPTY.")
Run Code Copy

Output

The set is NOT EMPTY.

2. Checking if Set is empty using Set length

The length of an empty set is zero. We can use this information to create a condition that checks the length of the given set, and verifies if the given set is empty.

We can use len() built-in function to get the length of the set.

For example, consider the following condition.

len(set_1) == 0

The above condition returns True if the set set_1 is empty, or returns False if the set is not empty.

Let us write an example program, where we take a set in set_1, and check if the set is empty.

Python Program

set_1 = set()

if len(set_1) == 0:
    print("The set is EMPTY.")
else:
    print("The set is NOT EMPTY.")
Run Code Copy

Output

The set is EMPTY.

Now, let us take a non-empty set in set_1, and run the program.

Python Program

set_1 = set({"apple", "banana", "cherry"})

if len(set_1) == 0:
    print("The set is EMPTY.")
else:
    print("The set is NOT EMPTY.")
Run Code Copy

Output

The set is NOT EMPTY.

Summary

In this tutorial of Python Sets, we learned how to check if a given Set is empty, in Python program, using NOT logical operator, or len() built-in function, with examples.

Related Tutorials

Code copied to clipboard successfully 👍