0

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

asked Sep 30, 2020 at 2:30
1
  • 4
    Just all(flags)? Commented Sep 30, 2020 at 2:30

3 Answers 3

1
finalFlags = False
if all(flags):
 finalFlags=True

Edit: Simplified per comment from Chris:

finalFlags = all(flags)
answered Sep 30, 2020 at 2:34
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you =) Do you suggest a course or book to learn python in depth. specially for AI
Sorry, I can not specifically recommend any books. There are tons of free courses out there though. Maybe start with Codecademy. They have a python machine learning course if you are interested in going in the AI direction.
0

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))
answered Sep 30, 2020 at 2:41

Comments

0

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)

runtime check

answered Sep 30, 2020 at 3:18

1 Comment

all() is the easiest way to use and also we can use any() also

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.