Saturday, December 28, 2024
Google search engine
HomeLanguagesPython – Check if a list is empty or not

Python – Check if a list is empty or not

In Python programming, determining whether a list is empty holds importance for effective data handling. This article delves into concise techniques for checking the emptiness of a list, enabling developers to efficiently validate if a list contains elements or is devoid of data. Through clear code examples, learn how to implement these methods and bolster your proficiency in Python’s list management.

Example

Input: ['Geeks', 'Geeks', 'Geeks', 'Geeks', ]
Output: Yes Not Empty
Input: [ ]
Output: Empty
Explaination: In first example the list have elements in it and not empty, in second case the list is empty having no elemnts in it.

How to Check if a List is Empty in Python

Check the Empty list using the len()

Let’s see how we can check whether a list is empty or not, in a less Pythonic way. We should avoid this way of explicitly checking for a sequence or list 

Python3




def Enquiry(lis1):
    if len(lis1) == 0:
        return 0
    else:
        return 1
 
# Driver Code
lis1 = []
if Enquiry(lis1):
    print("The list is not empty")
else:
    print("Empty List")


Output:

Empty List

Time complexity: O(n)
Auxiliary space: O(n), where n is the length of the list

Check the empty list using the implicit Booleans

Now let’s see a more Pythonic way to check for an empty list. This method of check is an implicit way of checking and more preferable than the previous one. 

Python3




def Enquiry(lis1):
    if not lis1:
        return 1
    else:
        return 0
 
# Driver Code
lis1 = []
if Enquiry(lis1):
    print("The list is Empty")
else:
    print("The list is not empty")


Output:

The list is Empty

Time complexity: O(n)
Auxiliary space: O(n), where n is the length of the list

Check the empty list using the PEP 8 recommended method

This is another method that allows us to determine whether a list in Python is empty. The most Pythonic method of checking the same is shown below.

Python3




list1 = {"a": 1, "b": 2, "c": 3}
list2 = []
 
if list2:
    print("list is not empty")
else:
    print("list is empty")


Output:

list is empty

Time complexity: O(1)
Auxiliary space: O(1)

Comparing a given list with an empty list using the != operator

The provided Python code checks whether the list lis1 is empty or not using an if statement. If the list is not empty, it prints “The list is not empty”; otherwise, it prints “Empty List.” This is achieved by comparing the list to an empty list using the inequality operator !=. In this specific case, where lis1 is initialized as an empty list, the condition evaluates to false, resulting in the output “Empty List.”

Python3




# Python code to check for empty list
lis1 = []
if lis1!=[]:
    print("The list is not empty")
else:
    print("Empty List")


Output

Empty List

Comparing given list with empty list using == operator

The subsequent if statement evaluates whether the lis1 is equal to an empty list, denoted by []. If the condition is true, meaning the list is indeed empty, the program prints “Empty List” to the console. If the condition is false, indicating that the list is not empty, the program instead prints “The list is not empty.”

Python3




# Python code to check for empty list
lis1 = []
if lis1==[]:
    print("Empty List")
else:
    print("The list is not empty")


Output

Empty List

This approach has the advantage of being concise and easy to understand. It is also generally faster than other approaches that involve looping through the elements of the list.

Check the empty list using try/except

To check if a list is empty or not using try/except in Python, you can use the following algorithm:

Algorithm:

Initialize the list. Try to access the first element of the list using lst[0]. If the above step raises an IndexError exception, then the list is empty. Otherwise, the list is not empty. Handle the exception by printing “Empty List”.Here’s the Python code implementation of the above algorithm:

Python3




# Python code to check for empty list
lst = []
 
try:
    lst[0]
    print("The list is not empty")
except IndexError:
    print("Empty List")


Output

Empty List

Time complexity: O(1), as accessing the first element of the list takes constant time.
Auxiliary space: O(1), as we are not using any extra space to perform this operation.

Check the empty list using the Numpy module

Example 1: If we have a NumPy array then the correct method in all cases is to use if .size. This size checks the size of the arrays and returns True or False accordingly. Example: 

Python3




# Numpythonic way to check emptiness
# Use of size
import numpy
 
def Enquiry(lis1):
    return(numpy.array(lis1))
 
 
# Driver Code
lis1 = []
if Enquiry(lis1).size:
    print("Not Empty")
else:
    print("Empty")


Output:

Empty

Example 2: This example shows the other case with a single 0 element, which failed in the previous cases. 

Python3




import numpy
 
def Enquiry(lis1):
    return(numpy.array(lis1))
 
# Driver Code
lis1 = [0, ]
if Enquiry(lis1).size:
    print("Not Empty")
else:
    print("Empty")


Output:

Not Empty

RELATED ARTICLES

Most Popular

Recent Comments