In this solution, we use the len() to check if a list is empty, this function returns the length of the argument passed. And given the length of an empty list is 0 it can be used to check if a list is empty in Python.
Using Count() The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count(). The below program uses this logic.
You can check if the list is empty in python using the bool() function. bool() function returns boolean value of the specified object. The object will always return True , unless the object is empty, like [] , () , {} . You can use the bool function for any of the list-like objects.
isEmpty() method of CollectionUtils can be used to check if a list is empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list.
if not myList:
print "Nothing here"
Empty lists evaluate to False in boolean contexts (such as if some_list:
).
I like Zarembisty's answer. Although, if you want to be more explicit, you can always do:
if len(my_list) == 0:
print "my_list is empty"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With