Check if Set is Empty

 

What You'll Learn: In this tutorial, you'll discover how to check if a set is empty in Python. Knowing whether a set is empty helps you make decisions in your code.

Method 1: Using the NOT Operator

You can check if a set is empty using the not operator. This method returns True if the set is empty, and False if it is not.

Example Code:

python
set_1 = set()
if not set_1:
    print("The set is EMPTY.")
else:
    print("The set is NOT EMPTY.")

Output: The set is EMPTY.

What's Happening Here?

  • not set_1 checks if set_1 is empty.

Example with a Non-Empty Set:

python
set_1 = {"apple", "banana", "cherry"}
if not set_1:
    print("The set is EMPTY.")
else:
    print("The set is NOT EMPTY.")

Output: The set is NOT EMPTY.

Method 2: Using the Length of the Set

The length of an empty set is zero. You can use the len() function to check the length of the set.

Example Code:

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

Output: The set is EMPTY.

What's Happening Here?

  • len(set_1) == 0 checks if the length of set_1 is zero.

Example with a Non-Empty Set:

python
set_1 = {"apple", "banana", "cherry"}
if len(set_1) == 0:
    print("The set is EMPTY.")
else:
    print("The set is NOT EMPTY.")

Output: The set is NOT EMPTY.

Try It Yourself: Fun Exercises

  1. Check Your Favorite Colors:
    • Create a set of your favorite colors.
    • Use both methods to check if the set is empty.
  2. Measure Your Reading List:
    • Make a set of book titles you've read.
    • Check if the set is empty before adding a new book.

Summary:

In this Python tutorial, we learned two ways to check if a set is empty: using the not operator and the len() function. These methods help you determine if a set has items or is empty. Keep experimenting and have fun with sets in Python!