89DEVs

Python: How to check if list is empty?

How do you check if a list is empty in Python?

In Python empty sequences like strings, lists and tuples evaluate False. While non-empty sequences evaluate True. Therefore, the easiest and most pythonic way of checking if a list is empty is to use a Truth check.

check if list is empty using if not

This method is the recommended method of checking if a list is empty, other methods can be found below. # check if list is empty using if not myList = [] if not myList: print('myList is empty') In this example, if not equals True because the list is empty and the print command is executed. myList is empty

check if list is empty using len()

If a list is empty or not, can also be checked using the len() function. This is not recommended, because it doesn't follow the Python style guides like PEP8. # check if list is empty using len() myList = [] if len(myList) == 0: print('myList is empty') The length of the list equals 0, because it is empty and has 0 elements. Therefore, the print command is executed. myList is empty Instead of comparing the length of the list to integer 0, it's also possible to use len() with the if not operator. And this shows why this way of checking for an empty list is not recommended. The len() function is simply not necessary, because if not on the list gives the same result. myList = [] if not len(myList): print('myList is empty') The length of myList is 0 and therefore not True, so the print command is executed. As mentioned, this way is not recommended. myList is empty

check if list is empty by comparing it to empty list

Another way to check if a list is empty can be found by comparing the list to an empty list. This solution is not recommended because a new empty list is created and this is a somewhat expensive operation and not necessary. # check if list is empty by comparing it to an empty list myList = [] if myList == []: print('myList is empty') The list is compared to an empty list and if the equation is True, the print command is executed. myList is empty

Conclusion

The recommended way of checking if a list is empty in Python is using the if not operator.

                
        

Summary


Click to jump to section