Home > Net >  Make a list of Boolean Function Output to check if all are True
Make a list of Boolean Function Output to check if all are True

Time:10-15

I am new to python and trying to check if multiple Boolean results of a function can be converted to a Boolean list.

A function loops through a list and produces the following output. "True False False" or "True True True"

I would like to create a function to check if all are True and return False if not (not all true). I tried the all() function but received the following errors. TypeError: 'NoneType' object is not iterable TypeError: 'bool' object is not iterable

CodePudding user response:

Please post the bit of code you are attempting. I will provide you a solution.

CodePudding user response:

Consider this solution

Code:

list_to_be_checked=[1,1,2,3]
results=[]
def test(t):
    for i in t:
        if i == 1:
            results.append(True)
        else:
            results.append(False)
def check(my_list):
    if all(my_list):
        return True # all elements in my_list are True
    return False  # else return False

test(list_to_be_checked)
print(check(results))

Output:

False

CodePudding user response:

You can set up a list with all your boolean values and then take advantage of the fact that a True boolean variable has a numeric value of 1 and a False of 0. So in a list where all elements are True, the sum of the list must be equal to its length:

my_list = [True, True, False, True]
print(sum(my_list)==len(my_list))

This will output False, because sum(my_list) evaluates to 3 and len(my_list) to 4.

  • Related