0

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?

2
  • Could be rewritten as return [str(bool(inner[3])) for inner in cata] Commented Sep 26, 2016 at 8:12
  • You are returning the strings 'True' and 'False' instead of the boolean values True and False. Are you certain this is what you want? Commented Sep 26, 2016 at 8:30

1 Answer 1

3

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]
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Also if I wanted to instead add up the numbers in a list, could I essentially use r = [int(x[3]) for x in cata ?
@SabafapBing, you could use sum(x[3]) to sum the numbers, int() can't take a list as argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.