DEV Community

Cover image for How to check if a list is empty in Python?
Isabelle M.
Isabelle M.

Posted on

How to check if a list is empty in Python?

Considering that Python list is one of the most used data structures, it's a given that at some point the need to check if a list is empty will arise.

There are several ways to do this, however, the most straightforward is to use a method called Truth Value Testing.

In Python, any object can be tested for truth value, including lists. In this context, lists are considered truthy if they are non-empty, meaning that at least one argument was passed to the list. So, if you want to check if a list is empty, you can simply use the not operator.

empty_list = []
non_empty_list = [1, 2, 3]

not empty_list # True
not non_empty_list # False
Enter fullscreen mode Exit fullscreen mode

The not operator is a logical operator that returns the opposite of the value it is applied to. In the above code example we can see that it returns True if the list is empty and False if the list is not empty.

While the not operator is the most straightforward and pythonic way to check if a list is empty, there are other ways to do this. For example, you can use the len() function. This function returns the length of the list, which is 0 if the list is empty.

empty_list = []
non_empty_list = [1, 2, 3]

len(empty_list) == 0 # True
len(non_empty_list) == 0 # False
Enter fullscreen mode Exit fullscreen mode

Another way is to compare the list to an empty list using the == operator.

empty_list = []
non_empty_list = [1, 2, 3]

empty_list == [] # True
non_empty_list == [] # False
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
rohit254 profile image
Rohit Kumar

Easily explain in simple language and codes. I like the content and want an depth blog on it can you write in it an depth blog?

I also write a blog on Python list I like it if anyone provides their valuable thoughts on it. Here is my blog link - surushatutorials.blogspot.com/2024...