Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How to check Booleans inside a for loop?

I'm without clues on how to do this. I've a list:

list_something = [5, 6, 8]

And I've a method is_valid()

def is_valid(number):
    return type(number) is int

How can I check at once if the 3 numbers are all Integers inside a for loop?

for item in list_something:

At the end of the for loop I need to have a variable called "all_list_something" and will have the value of True or False. If all the numbers in the list are Integer, the value is True. If only one fails to be Integer, the value will be false.

Any clues on the best way to achieve this?

Best Regards,

like image 526
André Avatar asked Aug 02 '26 08:08

André


2 Answers

A generator comprehension can improve readability over a map for some.

all_list_something = all(is_valid(x) for x in list_something)
like image 126
cmh Avatar answered Aug 07 '26 01:08

cmh


You can use all and map:

all_list_something = all(map(is_valid, list_something))

Using itertools.imap would allow this to short-circuit (meaning that if the first element is invalid, it never checks the rest):

import itertools
all_list_something = all(itertools.imap(is_valid, list_something))
like image 45
David Robinson Avatar answered Aug 07 '26 02:08

David Robinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!