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

How to check if a list is empty in Python?

 

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:

Example:

list= []

if not list:
   print('List is empty')
else:
   print('List is not empty')

Output

 

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.

Example:

list= []

if len(list) == 0
   print('List is empty')
else:
   print('List is not empty')

Output:

 

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.

Example:

list= []

if list== []:
   print('List is empty')
else:
   print('List is not empty')

Output:

 

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.

Example:

list= []

if list.__len__() == 0:
   print('List is empty')
else:
   print('List is not empty')

Output:

 

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.

Example:

import numpy as np

list= []
a = np.array(list)
if a.size == 0:
   print('List is empty')
else:
   print('List is not empty')

Output:

 

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.

Example:

list= []

if bool(list):
   print('List is empty')
else:
   print('List is not empty')

Output:

 

 

Leave a comment