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.
- Using the “if-not operator”: The not-operator reverses the false value.
- 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.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.