In Python, you can check if a list is empty using the len()
function or by directly testing the list’s truthiness.
Here’s an example using the len()
function:
my_list = []
if len(my_list) == 0:
print(“List is empty”)
else:
print(“List is not empty”)
In this example, we define an empty list my_list
and check if its length is equal to 0
using the len()
function.
Alternatively, you can check if the list is empty by testing its truthiness, since empty lists are considered “falsy” in Python:
my_list = []
if not my_list:
print(“List is empty”)
else:
print(“List is not empty”)
In this example, we use the not
operator to test if the list my_list
is “falsy”, which is equivalent to checking if it is empty. If the list is empty, the condition is True
and the “List is empty” message is printed. Otherwise, the “List is not empty” message is printed.
- sunny asked 1 month ago
- You must login to post comments
Please login first to submit.