A list is a frequently used data structure in Python. Therefore, users often need to determine if a list is empty or not.
There are several ways to do this. Some of the ways may appear to be more explicit while others take relatively less time to execute and hence, are endorsed by the developers of Python.
First, let’s take a look at the most “Pythonic” and recommended way to do determine if a list is empty. An empty data structure is always evaluated to false in Python, and the following method relies on this boolean interpretation of a data structure in the language.
As mentioned earlier, an empty list evaluates to false; when the
not operator is applied on false, the result is true and hence, the code inside the
if condition is executed.
# RECOMMENDED empty_list =  if not empty_list: print('The list is empty!') else: print('The list contains something.')
Now, let’s look at a method that seems obvious: the built-in length function.
len returns 0 if the list is empty.
empty_list =  if len(empty_list) == 0: print('The list is empty!') else: print('The list contains something.')
Lastly, consider another approach that seems pretty straightforward.
compare_with is another empty list and we compare our own list with it.
empty_list =  compare_with =  if empty_list == compare_with: print('The list is empty!') else: print('The list contains something.')
View all Courses