Check if Set Is Empty in Python
-
Check if Set Is Empty in Python Using the
len()
Function -
Check if Set Is Empty in Python Using the
bool()
Function -
Check if Set Is Empty in Python Using
set()
Method -
Check if Set Is Empty in Python Using the
not
Operator
This tutorial will discuss various methods to check if a set is empty in Python. We will define a method empty_set()
which returns True
if the set is empty, otherwise False
. This method can be useful where we want to perform actions on non-empty sets and skip empty sets.
Check if Set Is Empty in Python Using the len()
Function
The len()
function takes an object as input and returns its length. To check if a set is empty, we can check if its length is zero or not.
Example code:
def is_empty(a):
return len(a) == 0
a = set('a')
b = set()
print(is_empty(a))
print(is_empty(b))
Output:
False
True
Check if Set Is Empty in Python Using the bool()
Function
The bool()
method in Python returns True
if the input is not empty and False
if the input is empty. The example code below demonstrates how to check if a set is empty using the bool()
function.
def is_empty(a):
return not bool(a)
a = set('a')
b = set()
print(is_empty(a))
print(is_empty(b))
Output:
False
True
Check if Set Is Empty in Python Using set()
Method
The set()
method initializes an empty set. So if the given set is equal to set()
, it means it is empty.
Example code:
def is_empty(a):
return a == set()
a = set('a')
b = set()
print(is_empty(a))
print(is_empty(b))
Output:
False
True
Check if Set Is Empty in Python Using the not
Operator
The not
operator reverses the operand, returns True
is the operand is identified as False
, like the empty set, and returns False
is the operand is not empty.
def is_empty(a):
return not a
a = set('a')
b = set()
print(is_empty(a))
print(is_empty(b))
Output:
False
True