Reputation: 3
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
Reputation: 160367
You're return
ing 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])
yield
ing 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