Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

Is there a Pythonic way to check if a list (a nested list with elements & lists) is essentially empty? What I mean by empty here is that the list might have elements, but those are also empty lists.

The Pythonic way to check an empty list works only on a flat list:

alist = [] if not alist:     print("Empty list!") 

For example, all the following lists should be positive for emptiness:

alist = [] blist = [alist]               # [[]] clist = [alist, alist, alist] # [[], [], []] dlist = [blist]               # [[[]]] 
like image 262
Ashwin Nanjappa Avatar asked Oct 20 '09 09:10

Ashwin Nanjappa


People also ask

How do I know if a nested list is empty?

You can check if the nested list is empty by using the not and any() function of python. any function will check if any of the lists inside the nested lists contain any value in them. If not, then it'll return True when means the nested list is empty.

How do I check if a list is empty in Python?

In this solution, we use the len() to check if a list is empty, this function returns the length of the argument passed. And given the length of an empty list is 0 it can be used to check if a list is empty in Python.


1 Answers

Use the any() function. This returns True if any list within the list is not empty.

alist = [[],[]] if not any(alist):     print("Empty list!")  >> Empty list! 

see: https://www.programiz.com/python-programming/methods/built-in/any

like image 158
Nahuel Brandán Avatar answered Sep 20 '22 13:09

Nahuel Brandán