Check for an empty Set in Python
This post will discuss how to check for an empty set in Python.
Python 3.x introduced the syntax for set literals – curly brackets surrounding the contents of a mutable set. However, there is no literal for an empty set in Python. This is because the set literals are distinguished from dictionaries by the absence of key-value pairs (separated by colons). Therefore, {} syntax represents an empty dictionary while set() represents an empty set.
1. Using len() function
A simple solution to check if a set is empty is using the len() function. It returns the total number of items in a set. Since an empty set has a length of 0, you can use this as:
|
1 2 3 4 5 6 7 8 9 10 11 |
if __name__ == '__main__': s = set() isEmpty = (len(s) == 0) if isEmpty: print("Set is empty") else: print("Set is not empty") |
2. Using == operator
Another preferred explicit way to check for an empty set is to compare the set with an empty set set() using the == operator. The following example demonstrates this:
|
1 2 3 4 5 6 7 8 9 10 11 |
if __name__ == '__main__': s = set() isEmpty = (s == set()) if isEmpty: print("Set is empty") else: print("Set is not empty") |
3. Checking for an empty set in boolean contexts
Finally, if you need to check if a set is empty in boolean contexts, you can use the following code:
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': s = set() if len(s): print("Set is not empty") else: print("Set is empty") |
You can even skip the comparison. This works since an empty set is interpreted as False in a boolean context in Python.
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': s = set() if s: print("Set is not empty") else: print("Set is empty") |
That’s all about checking for an empty Set in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)