Reputation: 25554
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,
Upvotes: 2
Views: 205
Reputation: 78590
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))
Upvotes: 8
Reputation: 7357
Since the question asks about how to do it in a for loop, I thought I'd include such an answer:
all_list_something = True
for item in list_something:
if not is_valid(item):
all_list_something = False
break
But really, David or cmh's answer is the way to go.
Upvotes: 4
Reputation: 10927
A generator comprehension can improve readability over a map for some.
all_list_something = all(is_valid(x) for x in list_something)
Upvotes: 10