How to check list is empty or not?
Introduction
In this blog, you will know that, how can we check whether the list is empty or not in python.
Suppose you have a list like as follows
list = [];
As we know that this list is empty but it might be possible when you are getting the data from api or file or database etc. On that time list might be empty so while fetching data, we always check list is empty or not. So there are two ways to check which are as follows
1. Using the implicit booleanness
if not list: print("List is empty")
In above example, we are just check with the not operator to check that following example will clear you more about this
>>> list = [] >>> not list // This will print True >>> list = [1, 2, 3, 4] >>> not list // Now this will written False
2. Using len() function
We can also do the same using len() function, which checks the length of an list or string or tupple etc. example is as follows
if not len(list): print("List is empty")
In above example len() function will give the result in numbers. So if list will be empty the length of the list will be 0. After then we are using the not operator because 0 is equal to False in python but if condition works on True value.
Thank You 😊😊😊