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

前端 未结 7 1666
栀梦
栀梦 2020-12-29 05:56

Is there a Pythonic way to check if a list (a nested list with elements & lists) is essentially empty? What I mean by

7条回答
  •  醉酒成梦
    2020-12-29 06:00

    I don't think there is an obvious way to do it in Python. My best guess would be to use a recursive function like this one :

    def empty(li):
        if li == []:
            return True
        else:
            return all((isinstance(sli, list) and empty(sli)) for sli in li)
    

    Note that all only comes with Python >= 2.5, and that it will not handle infinitely recursive lists (for example, a = []; a.append(a)).

提交回复
热议问题