How to Check If List is Empty in Python

Here are seven ways to check if a list is empty in Python.

  1. Using not in operator
  2. Using len() method
  3. By comparing with an empty list
  4. Check the empty list using the PEP 8 recommended method
  5. Comparing a given list with an empty list using != operator
  6. Using list comprehension + len()
  7. Using NumPy module

Method 1: Using the not in operator

To check if a list is empty in Python, you can use the not operator with the if condition. The not operator checks the existence of a specified value inside a given sequence, but it returns a value opposite to that of the in operator.

listA = []

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

Output

List is empty

Method 2: Using the len() Function

The len() function is used to find the number of elements in the list. To check if the list is empty using len(), pass the empty list to the len() function, and if we get 0, that means the list is empty.

listA = []

if not len(listA):
  print('List is empty')
else:
  print('List not empty')

Output

List is empty

We can also use the double equal to compare with 0 to check if the list is empty.

listA = []

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

Output

List is empty

Method 3: Compare the empty list with another empty list.

Compare our current list to [ ]; we will get an idea if the list is empty.

listA = []

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

Output

List is empty

Method 4: Checking an empty list using the PEP 8 recommended method

The PeP8 allows us to determine whether a list in Python is empty.

list1 = {"A": 1, "B": 2, "C": 3}
list2 = []

if list2:
  print("list is not empty")
else:
  print("list is empty")

Output

list is empty

Method 5: Comparing a given list with an empty list using != operator

import numpy as np

list2 = []

if list2 != []:
  print("The list is not empty")
else:
  print("Empty List")

Output

Empty List

Method 6: Using list comprehension + len() 

lst = ['data', 'base', 'fire', 'base']

x = ["not empty" if len(lst) > 0 else "empty"]

print(x)

Output

['not empty']

Method 7: numpy module

import numpy as np

list2 = []

result_array = np.array(list2)

if result_array.size == 0:
  print('Empty list')
else:
  print('List is not Empty')

Output

Empty list

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.