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] # [[[]]]
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With