3 Ways to Check if List is Empty in Python

Table of Contents

In this article, we will cover 3 ways to check if the list is empty in Python.

To check if Python List is empty, we can write a condition if the length of the list is zero or not; or we can directly use the list reference along with not operator as a condition in if statement.

Check if List is Empty with not operator

We will initialize an empty list, and check programmatically if the list is empty or not using not operator and list reference.

myList = []
if not myList:
print(‘The list is empty.’)
else:
print(‘The list is not empty.’)

more info about not operator

The not operator negates the truth value of its operand. A true operand returns False. A false operand returns True.

>>> not True
False

>>> not False
True

More example of not operator

>>> not 0
True
>>> not 42
False
>>> not True
False

>>> not “”
True
>>> not “Hello”
False

>>> not []
True
>>> not [1, 2, 3]
False
>>> not {}
True
>>> not {“one”: 1, “two”: 2}
False

 

Check if List is Empty using len() function

we will initialize an empty list, and check programmatically if the list is empty or not using len() function.

myList = []
if (len(myList) == 0):
print(‘The list is empty.’)
else:
print(‘The list is not empty.’)

more info about len()
The len() function returns the number of items (length) in an object.

The len() function takes a single argument, which can be

  • sequence – string, bytes, tuple, list, range OR,
  • collection – dictionary, set, frozen set

example of len()

languages = [‘Python’, ‘Java’, ‘JavaScript’]

# compute the length of languages
length = len(languages)
print(length)

# Output: 3

Check if List is Empty using list Comparison

myList = []
if (len(myList) == []):
print(‘The list is empty.’)
else:
print(‘The list is not empty.’)

Which is the fastest?

From our testing, we can see that the first method is not only 50% faster than method 2 and 75% faster than method 3.

It’s clearly the best method in terms of runtime performance.

Table of Contents

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn

You might also like