Python: Check if a list is empty or not

How to check if a list is empty or not in python ?

In this article we will discuss about different ways to check if a list is empty or not. As we know in python, lists are used to store multiple values in an ordered sequence inside a single variable.  Each element inside the list is called an item.

Syntax : my_list = [ element1, element2, element3, .....]

where,

  • elements/items are placed inside square brackets [].
  • items are separated by , symbol.
  • It can contain any number of items.
  • elements can be of different types i.e string, float, integer etc.

Method-1 : Check if a list is empty using ‘not’ operator in python

A sequence object in python is implicitly convertible to bool. If the sequence is empty it will be evaluated to False else True. So just by using an if statement we can check the list is empty or not.

#Program :

# empty list created
my_list = []
# Here empty list object will evaluate to False
if not my_list:
    print('List is empty')
else:
    print('List is not empty')
Output :
List is empty

Method-2 : Check if list is empty using len() function

By using the len(), we can get the size of list. If the size of list is zero then it is empty list.

Example program :

#Program :

# empty list created
my_list = []

# Check if list's size is 0
if len(my_list) == 0:
    print('List is empty')
else:
    print('List is not empty')
Output :
List is empty

Method-3 : Check if list is empty by comparing with empty list

Empty list is denoted by [] this.  So by comparing our list object with [] , we can confirm the list is empty or not.

#Program :

# empty list created
my_list = []

# Check if list object points to literal []
if my_list == []:
    print('List is empty')
else:
    print('List is not empty')
Output :
List is empty

Method-4 : Check if list is empty using __len__()

We can get the size of list by calling __len__() function on the list object.  If the list size is equals to zero then the list is empty.

Let’s see an implementation of it.

#Program :

# empty list created
my_list = []

# Check if list's size is 0
if my_list.__len__() == 0:
    print('List is empty')
else:
    print('List is not empty')
Output :
List is empty

Method-5 : Check if a list is empty using numpy

First convert list inti Numpy array then check the size of Numpy array.

  • If the size of Numpy array is zero then the list is empty
  • If the size of Numpy array is greater than zero then list is not empty.

Let’s see an implementation of it.

#Program :

import numpy as np
# empty list created
list_of_num = []
arr = np.array(list_of_num)
if arr.size == 0:
    print('List is empty')
else:
    print('List is not empty')
Output :
List is empty