how to check if the list is empty python

How to check if the given list is empty in Python ?

This tutorial guides you on how to check if the given list is empty in Python programming language using if condition and Boolean operation not.

Check if the given list is empty in Python

how to check if the list is empty python

For example, the following is the given input list.

>>> l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]

To check if the given list is empty or not using Python, try running the following logic which uses Boolean operation (not l) as operand in if condition.

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

Output

list is not empty

Boolean Operations – and, or, not

The following are the Boolean operations, ordered by ascending priority. Any object can be tested for truth value (true/ false) using if or while condition with any Boolean operations as operand as show in the example above.

Operation      Result
x or y             if x is false, then y, else x
x and y          if x is false, then x, else y
not x              if x is false, then True, else False

using len() in if condition

You may think to check length of the given list explicitly and check whether it contains elements or it is empty as shown below.

Don’t Do : For example,

>>> l = []

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

output

list is empty

But that’s not the best practice.

Do this : Instead check if the given list is empty or not in the following ways: using len() function and Boolean operations as shown below.

#given input list -empty list
>>> l = []

#using len() function alone
>>> if len(l):
...     print('list is not empty')
... else:
...     print('list is empty')
...
list is empty

#using len() and Boolean operations
>>> if not len(l):
...     print ('list is empty')
... else:
...     print('list is not empty')
...
list is empty

That’s it. You had learnt the best practice to check if the list is empty or not. Also, learnt how to use Boolean operations in if condition.

Hope it is helpful 🙂

You’ll also like:

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments