Is there a Pythonic way to check if a list (a nested list with elements & lists) is essentially empty? What I mean by
If you do not need to iterate through the lists, simpler is better, so something like this will work:
def empty_tree(input_list):
"""Recursively iterate through values in nested lists."""
for item in input_list:
if not isinstance(item, list) or not empty_tree(item):
return False
return True
However, it would be good to separate the recursive iteration that you will most probably reuse elsewhere and checking that it returns no elements. This way if the mechanism of iteration changes you need to implement the change in one place. For instance when you need to support arbitrary nested iterables, or nested dicts.
def flatten(input_list):
"""Recursively iterate through values in nested lists."""
for item in input_list:
if isinstance(item, list): # Use what ever nesting condition you need here
for child_item in flatten(item):
yield child_item
else:
yield item
def has_items(seq):
"""Checks if an iterator has any items."""
return any(1 for _ in seq)
if not has_items(flatten(my_list)):
pass