Check if list is empty Python
In this post, you will know how to check whether a list is empty or not in Python. There are many ways to check this, we will mention most of them with simple examples.
A list is a sequence of indexed and ordered values, like an array. It is mutable, which means we can change the order of elements in a list. It contains a list of any type of data objects with a comma separated and enclosed within a square bracket. Each element of the list has an index, starting with 0, 1 and so on. In the development process, we may come to the situation where we need to check whether the list is empty or not.
Check if list is empty using len() method
Python len() method returns the number of elements in the list. We can use this to check if the length of a list is equal to zero or not. This process is considered an unpythonic way and generally not recommended.
a = []
if not len(a):
print("List a is empty")
b = [10, 33, 42, 24]
if not len(b):
print("List b is empty")
Output of the above code -
List a is empty
Check if list is empty using If not seq
In Python, a boolean value of an empty list is always False and non-empty list is always True. Accordingly, we can essentially regard the list as a predicate returning a boolean value and check whether a list is empty or not. This solution is highly pythonic and most recommended.
a = []
if not a:
print("List a is empty")
b = [10, 33, 42, 24]
if not b:
print("List b is empty")
Output of the above code -
List a is empty
Compare list with an empty list
We can also determine whether a list is empty or not by directly comparing it with an empty list. This process returns True if the given list matches with the empty list. But this process is also very unpythonic.
a = []
if a == []:
print("List a is empty")
b = [10, 33, 42, 24]
if b == []:
print("List b is empty")
Output of the above code -
List a is empty
Related Articles
Python zip function
range and xrange in Python
2d arrays in Python
splitlines in python
Calculator program in python
strip function in Python
casefold in Python
Prime factors of a number in Python
Python nonlocal keyword
Greatest common divisor Python recursive
Python String isalpha() Method
Program to print ASCII Value of a character
Python program to sort words in alphabetical order
Python convert list to numpy array
How to shuffle a list in Python
*args and **kwargs in Python
Hollow diamond pattern in python
Stemming and Lemmatization in Python
Python | Generate QR Code using pyqrcode module