/  Technology   /  How do I check if a list is empty?

How do I check if a list is empty?

How do I check if a list is empty?

 

Python provides various ways to check if a list is empty or not, so let’s learn about these methods in this article.

 

A sequence object like a list, tuple or a string, can be implicitly converted to bool. The bool function evaluates False if the sequence is empty, else it evaluates to True. So, we can use an if statement on this sequence object for checking if it’s empty or not.

 

Using the ‘not’ operator:

 

Using len() function:

The len() function takes in a sequence like a list, tuple, set, etc, as an argument and returns the number of elements in that sequence i.e., it returns the size of the sequence.

Now we pass our empty list to the len() function and once we get the size, we can confirm if it’s empty or not by comparing it with 0.

 

By Comparing it with an empty list:

Empty square brackets [] in python point to an empty list. So, we compare our list object with [] to know if it’s empty or not.

 

Using __len()__ list method:

Python is enabled with various list methods. The len() function is one of them. It returns the number of elements present in a list which gives the size of the list.

list.__len__()

From here, it’s similar to the above method. The size of our list is found out by calling the __len__() function using the list object and once we get the size, we can confirm if it’s empty or not by comparing it with 0.

 

Using numpy:

We import the numpy package before implementing this method. We first convert a Python list to a numpy array

np.array(list)

And then check the size of the numpy array using the attribute size. If the size of the numpy array is zero then our list is empty.

 

Using bool() function:

As we have discussed, the bool() function works based on Truth Value Testing. So the function returns True if the list isn’t empty and the if block gets executed.

Leave a comment