Each variable in programming has an initial state, and the Set data structure is no different. Programmers often initialize an empty set, which is then populated later.
To create an empty Set in Python, you can use the set() Constructor without any arguments. It looks like this: empty_set = set().
empty_set = set() print(empty_set) # Output: set()
However, do not use {}(curly braces) because it will initialize an empty dictionary, not set.
empty_set = {} print(empty_set) print(type(empty_set)) # Output: {} # <class 'dict'>
So, what you are initializing is not a Set, but in reality, it is a Dictionary that only accepts key/value pairs.
Check if a Set is empty
The easiest way to check if a Set is empty is to check its length with len(empty_set) == 0. The length of an empty object is always 0. If we get True, the Set is empty; otherwise, it is not.
empty_set = set() print(len(empty_set) == 0) # Output: True
If the Set has some elements, the len() method will return a number other than 0.
filled_set = {11, 21, 19} print(len(filled_set) == 0) # Output: False
This approach is very efficient and highly recommended.
Implicit boolean check
You can also use if not operator to check whether a set is empty or not. For example, if not empty_set: … that would be True if the set is empty.
filled_set = {11, 21, 19} if not filled_set: print("Set is empty") else: print("Set is not empty") # Output: Set is not empty
Let’s check with an actual empty set:
empty_set = set() if not empty_set: print("Set is empty") else: print("Set is not empty") # Output: Set is empty
It is the Pythonic way that is readable and concise.