Skip to content

Python check if the list is not empty | Example code

  • by

You can list empty or not using the length of the list in Python.

l2 = []

if l2:
    print("the list is not empty")
else:
    print("the list is empty")

Output: the list is empty

But it will not work in a different type of list

a = []
a = [[], []]
a = [[], [], [[], []]]

Python check if the list/sublist is not empty Example

Simple example code used a function that recursively checks the items within sublists:

def is_empty(l):
    return all(is_empty(i) if isinstance(i, list) else False for i in l)


a = []
print(is_empty(a))

a = [[], []]
print(is_empty(a))

a = [[], [], [[], []]]
print(is_empty(a))

Output:

Python check if the list is not empty

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

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading