Python check if the list is empty | Example code

You can simply check if the list is empty using the if statement in Python. Use the len() methods and if len is zero then the list is empty.

Another method use bool() function because empty lists are considered False in Python. So would return False if the empty list was passed as an argument.

Python check if the list is empty example

Simple example code.

Using PEP 8 recommended method

This is the most Pythonic way of checking the empty list. Since an empty list is False so if statement block executes.

list1 = []

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

Output:

Python check if the list is empty

Using the bool() function

If bool() return true means list is not empty otherwise return false means list is empty.

list1 = []
list2 = [1, 2, 3]

print(bool(list1))
print(bool(list2))

Output:

False
True

Using if statement with Using len()

list1 = []

if len(list1):  # Or len(l2) == 0
    print("list is not empty")
else:
    print("list is empty")

Output: list is empty

Do comment if you have any doubts and suggestions on this Python list topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

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