Reputation: 3
I'm trying to find away to do this in a shorter way I don't like not using else in the end because it looks weird without it. This works for me for some reason. If I add the, " else: return True" it will only look at the first true from the list and then return True but won't check the rest... and will end the function
b = [[True, True, True], [True, True, True], [True, True, False]]
for i in range(3):
for j in range(3):
if b[i][j] == False:
return False
return True
Upvotes: 0
Views: 45
Reputation: 114478
You can use either all
or any
to do this:
all(all(x) for x in b)
OR
not any(not y for x in b for y in x)
In either case, the value of the expression will be the same as the return value of your original function. Like your original loop, both of these expressions are short-circuiting: they will stop as soon as a False
element in encountered in the nested lists.
In your original code, returning True
on the first element naturally ends the function. That's just how return
works. If you absolutely must have an else
clause to please your inner aesthete (I would recommend against it), use else: continue
instead. This is totally superfluous (and therefore generally undesirable), but it will instruct the loop to continue until a False
is found instead of returning from the function immediately.
Upvotes: 1
Reputation: 3563
I guess a pretty short way to accomplish this would be:
return all(i for l in b for i in l)
Upvotes: 2