How to Check if a Python Set is Empty?

There are three main ways to check if a set is empty:

  1. Implicit: Pass the set into a Boolean context without modification. Python will automatically convert it to a Boolean using bool().
  2. Explicit: Pass the set into the bool() Function.
  3. Comparison: Compare the set with the empty set like so: my_set == set()

Let’s dive into each of those next.

Way 1: Implicit Boolean Conversion (If Condition)

How to Check if a Set is Empty in an If Statement?

You can check if a set is empty by simply passing the set into the if condition without modification (e.g., if my_set: ...). Python will automatically associate a Boolean value to each object in those contexts.

  • If the set is empty, the condition will evaluate to False because all empty container types are automatically converted to False in a Boolean context. The else branch is executed.
  • If the set is not empty, the condition evaluates to True. The main if branch is executed in that case.

Here’s an example:

s = set()
if s:
    print('set is not empty')
else:
    print('set is empty')

# Output: set is empty

You can also invert the condition to if not s: ... in order to execute the main if branch if the set is empty:

s = set()
if not s:
    print('set is empty')

# Output: set is empty

πŸ‘‰ Recommended Tutorial: The not inversion operator in Python

Way 2: Pass Set into bool() Function

You can pass the set into the bool() function and invert it using the not operator to check if the set is empty. So, the expression not bool(my_set) will return True if my_set is empty.

print('Set is empty?', not bool(set()))
# Set is empty? True 

print('Set is empty?', not bool({1, 2, 3}))
# Set is empty? False 

Way 3: Use Equality Operator ==

You can check if a set is empty by comparing it to an empty set using Python’s equality operator ==. The expression my_set == set() compares the set my_set against the empty set. Even if both point to different objects in memory, the equality operator will still evaluate to True if both are empty, and False otherwise.

Here’s an example where we create a non-empty set, check if it is empty, remove an element, and check again:

my_set = {'Alice'}

print('Set is empty?', my_set==set())
# Set is empty? False 

my_set.pop()

print('Set is empty?', my_set==set())
# Set is empty? True 

The set.pop() method simply removes an element from the set, so it becomes empty.

Learn More

You can find out more about checking if a list is empty in our blog tutorial on the topic:

πŸ‘‰ Recommended Tutorial: How to Check if a List is Empty?