Sabafap Bing
Sabafap Bing

Reputation: 3

How do I check for an empty nested list in Python?

Say I have a list like

cata = [["Shelf", 12, "furniture", [1,1]],
        ["Carpet", 50, "furnishing", []]]

and I want to find out in each nested list if it's empty or not.

I am aware of using for loops to iterate through the lists, and if statements to verify as I have in a function

def myfunc(cata):
    for inner in cata:
        for inner_2 in inner[3]:
            if inner_2:
                return "True"
            else:
                return "False"

However instead of returning:

'True'
'False'

All I get is:

'False'

Is there some method of searching nested loops that I'm missing?

Upvotes: 0

Views: 1021

Answers (1)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160367

You're returning from the function, that essentially means that you don't evaluate every element.

Apart from that for inner_2 in inner[3]: will not do what you want because it won't execute for empty lists (it doesn't have elements to iterate though!). What you could do is go through each list and yield the thuth-ness of inner[3]:

def myfunc(cata):
    for inner in cata:
        yield bool(inner[3])

yielding will make the function a generator that can be iterated over and return your results:

for i in myfunc(cata):
    print(i)

Prints:

True
False

Of course, this can easily be transformed to a list comprehension that stores the results:

r = [bool(x[3]) for x in cata]

With r now holding:

[True, False]

Upvotes: 3

Related Questions