How to Create an Empty Set in Python

To create an empty Set in Python, you can use the “set() function and not pass any arguments.” However, do not use empty curly braces {} because it will create an empty dictionary, not set.

empty_set = set()

print(empty_set)
print(type(empty_set))

Output

set()
<class 'set'>

We created an empty list and printed it in the console using the print() function. We also printed the data type using the type() function.

How to check if a Set is empty in Python

You can use the following methods to check if a set is empty in Python.

  1. Using the “if-not operator”: The not-operator reverses the false value.
  2. Using len(): The set is empty if the len() function returns 0.

Method 1: Using the if-not operator

The not-operator can reverse the false value while using with if statement.

data_set = set()

if not data_set:
  print ("Set is empty")
else:
  print ("Set is not empty")

Output

Set is empty

If you assign values to the empty set, the above code’s else block will be executed.

data_set = set({11, 21})

if not data_set:
  print ("Set is empty")
else:
  print ("Set is not empty")

Output

Set is not empty

The declared set has two elements, so the set is not empty and executes the else block.

Method 2: Using the len() function

The len() is a built-in Python function that returns the length or size of the iterator. 

If you compare the result of len(set()) to 0 and if it returns True, then the set is empty otherwise not empty.

Use the double equals(==) operator to check equality in Python.

data_set = set()

if len(data_set) == 0:
  print ("Set is empty")
else:
  print ("Set is not empty")

Output

Set is empty

Similarly, if you assign values to an empty set, it won’t return 0 lengths; hence, it is not an empty set.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.