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

How to check if a nested list is essentially empty?

How to check if a nested list is essentially empty?

 

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

https://www.i2tutorials.com/list-comprehensions/ 

 

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():

Refer to this article for a better understanding of how isinstance() works

https://www.i2tutorials.com/type-and-instance/

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.

Leave a comment