/  Technology   /  How to check if a nested list is essentially empty in Python?
How to check if a nested list is essentially empty in Python

How to check if a nested list is essentially empty in Python?

 

Using for loop:

In this approach we defined a function that accepts a list of lists named list_of _lists that checks if all sub-lists present in it are empty or not. 

 

Using list comprehension:

Refer to this article for a better understanding of how list comprehension works list comprehension

 

The one-liner code written using the list comprehension returns a list of boolean values, where each element in this boolean list represents a sublist from our main list list_of_lists. If a sub-list is empty, then the respective element of this boolean list will be True, else it’s False.

 

We then pass this boolean list to the all() function which checks if all elements in this boolean list are True or not. If all the elements in the boolean list elements are True, then it means that all the sub-lists in our main list list_of_lists are empty.

 

Using isinstance(),all(),map():

Example:

def function(list_of_lists):
   for list in list_of_lists:
      if list:
         return False
   return True

list_of_lists = [ [], [], []]
if function(list_of_lists):
   print('List of Lists is empty')
else:
   print('List of Lists is not empty')

Output:

 

Refer to this article for a better understanding of how isinstance() works Type-and-instance

Example:

lists_of_lists = [ [], [], [], []]
if all([not sublist for sublist in list_of_lists]):
   print('List of Lists is empty')
else:
   print('List of Lists is not empty')

Output:

 

The map() function applies a given function to each item of an iterable(any sequence like list, tuple etc,.) and it returns a list of iterables

map(fun,iter)

fun is the function to which the map() passes each element of a given iterable.

iter is an iterable which is to be mapped.

 

The all() function as discussed checks if all elements in this new list formed are empty or not and returns True if found.

Example:

def fun(main_list):
   if isinstance(main_list, list):
      return all( map(list_of_lists, main_list) )
   return False

list_of_lists = [[],[]]
if not any(list_of_lists):
   print("List of lists is empty")

Output:

 

Leave a comment