check if list is empty in python

In this tutorial you will understand four technique to check if list is empty in python or not and will understand, which one is the best technique according to PEP 8 style guide.

Empty list in python

There are four ways of doing this

  • If not sequence:

In python programming, empty list return false as a boolean value and non-empty list return true as a boolean value. So you can easily check you list whether it is empty or not. See the below example of implementing “if not seq” method for checking list. According to PEP 8 style guide this the more pythonic way of checking for empty list in python.

x=[]
if not x:
   print("list is empty")
else:
   print("list is not empty")

Output:

list is empty
  • len() function

The another way of checking empty list in python is by using len() function. len() function is used to check length of list, so if the length of list is zero then it means list is empty and if the length of the list > zero, then it means list is not empty. This is less pythonic way of checking empty list in python.

x=[]
if len(x)==0:
   print("list is empty")
else:
   print("list is not empty")

Output:

list is empty
  • Comparison with empty list

The another way of checking empty list in python is by comparing the list with empty one. If both the list are equal then, it means list is empty otherwise list is not empty. This method is non-pythonic way of checking empty list in python.

x=[]
if x==[]:
   print("list is empty")
else:
   print("list is not empty")

Output:

list is empty
  • num pythonic way

The last method of checking empty list in python is by using numpy package which is used for numeric calculation in python. Here we are checking size of list, if list is having a size, than it means list is not empty otherwise list is empty. This method is also not recommended by PEP 8 style guide.

import numpy
def check(list1):
   return(numpy.array(list1))

list1=[]
if check(list1).size:
   print("list is not empty")
else:
   print("list is empty")

Output:

list is empty
Was this article helpful?
YesNo

1 thought on “check if list is empty in python”

  1. Pingback: buy backlinks uk

Leave a Comment