Python – Check if Set is NOT Empty

Python – Check if Set is NOT Empty

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

In this tutorial, we shall discuss two ways to check if the set is not empty.

  1. Use the set as a condition in if else statement
  2. Use len() built-in function to check the size of set

1. Checking if Set is NOT empty using Set as condition

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

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

Python Program

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

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

Output

The set is NOT EMPTY.

Now, let us take an empty set in set_1, and run the program.

Python Program

set_1 = set()

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

Output

The set is EMPTY.

2. Checking if Set is NOT empty using Set length

The length of a non-empty set is greater than 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 NOT 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 NOT empty, or returns False if the set is empty.

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

Python Program

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

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

Output

The set is NOT EMPTY.

Now, let us take an empty set in set_1, and run the program.

Python Program

set_1 = set()

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

Output

The set is EMPTY.

Summary

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

Related Tutorials

Code copied to clipboard successfully 👍