Register Login

Python: Check if Set is Empty

09 Apr 2020 7:49 am || 0

In this article, we will learn how to check whether a set is empty or not. A set in python is a mutable data structure. Python sets are written within curly brackets and consist of unique items. To check if a set is an empty or not we have many built-in function and operators.

We can check if Python list is empty using:

  1. not operator
  2. len() function
  3. comparing with another empty set

Let us understand it more briefly with the help of an example.

Example 1: Using the not Operator

# Initializing an empty set
MySet = {}
# Using not operator
if not MySet:
    print ("set is empty")
else:
    print ("set is not empty")

Output

set is empty

Explanation

In the above example, we created an empty set ‘MySet’. Then we used a not operator to reverse the false value.

In python, an empty set always evaluates to false. So when we passed an empty set to the if condition it’ll be evaluated to false. But the not operator reverses the false value to true value.

Thus the if condition is set to true. And we got “set is empty” as an output.

Example 2: Using the len() Function

# Initializing an empty set
MySet = {}
# Using len() function
Length_MySet = len(MySet)
# Using if-else Statement
if Length_MySet == 0:
    print ("set is empty")
else:
print ("set is not empty")

Output

set is empty

Explanation

In the above example, at first we initialized empty set ‘MySet. Then we used a built-in function len() to calculate the length of the set and stored it in the variable Length_set . Then we used if statement to check if the length of the list equals to zero or not.

If the condition sets to be true then the set is empty. Otherwise, the set is not empty.   

Example 3: Comparing with Another Empty Set

# Initializing an empty set ‘MySet1’
MySet1 = {'Hello', 'World' }
# Initializing an empty set ‘MySet2’
MySet2 = {}
# Comparing both the set
if MySet1 == MySet2:
print('The set is empty!')
else:
print('The set is not empty!')

Output

The set is not empty!

Explanation

In the above example, we initialized two set MySet1 and MySet2. Suppose we have to check for a set MySet1 if it is empty or not. Then we can do so by initializing an empty set say MySet2. And then comparing ‘MySet1’ with ‘MySet2’ using the decision making statement i.e if-else condition. If ‘MySet1’ is equal to ‘MySet2 then that means MySet1 is an empty set. Else it is not empty. And this is how we can check for an empty set by comparing it with another empty set.

Conclusion

In this article, we saw three different ways to check for an empty set. The three ways we discussed above are:

  • Using not
  • Using len()
  • Comparison with an empty set.