I am new to python
I have a list of flags. and that list has a variable length. I want to check if all the variables in that list are true
I have tried
if (all in flags[x]==True):
finalFlags[x-1]=True
But that turned the final flag true when only one flag is true
3 Answers 3
finalFlags = False
if all(flags):
finalFlags=True
Edit: Simplified per comment from Chris:
finalFlags = all(flags)
2 Comments
Since you didn't post an example, i can suppose like this:
my_flags = [True, False, True, True, True, False]
valid_flags = 0
for flag in my_flags:
if flag == True:
valid_flags += 1
if len(my_flags) == valid_flags:
print("Total match")
else:
print("Matched ", valid_flags, " out of ", len(my_flags))
Comments
all and any functions can be used to check the boolean values inside the list.
test_list = []
all(iterable) returns True if all elements of the iterable are considered as true values (like reduce(operator.and_, iterable)).
any(iterable) returns True if at least one element of the iterable is a true value (again, using functional stuff, reduce(operator.or_, iterable)).
When you need to check all the values are true then you can use all() function as follow
all(test_list) #will return true
Also, you can use any() to check all values that are true but at this time, You need to convert the list elements from true to false and check whether if any true is there we can say there is a false in original list and we need to return false also when any() returns false which means there is no true value so in the original list we don't have true values
not all(not element for element in data)
all(flags)?