Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a predicate evaluates true for all elements in an iterable in Python

Tags:

python

I am pretty sure there is a common idiom, but I couldn't find it with Google Search...

Here is what I want to do (in Java):

// Applies the predicate to all elements of the iterable, and returns // true if all evaluated to true, otherwise false boolean allTrue = Iterables.all(someIterable, somePredicate); 

How is this done "Pythonic" in Python?

Also would be great if I can get answer for this as well:

// Returns true if any of the elements return true for the predicate boolean anyTrue = Iterables.any(someIterable, somePredicate); 
like image 395
Enno Shioji Avatar asked Mar 07 '11 08:03

Enno Shioji


People also ask

How do you check if all values are true in Python?

Python all() Function The all() function returns True if all items in an iterable are true, otherwise it returns False. If the iterable object is empty, the all() function also returns True.

How do you check a condition for all elements in a list Python?

We can use all() , to perform this particular task. In this, we feed the condition and the validation with all the elements is checked by all() internally. This function can also be used to code solution of this problem. In this, we just need to process the loop till a condition is met and increment the counter.

How do you check if all elements of a list are true?

The Python all() function returns true if all the elements of a given iterable (List, Dictionary, Tuple, set, etc.) are True, else it returns False. It also returns True if the iterable object is empty.

How do you check if all values are false?

sum(data) represents the addition of 1 and 0 with respective values of True(1) and False(0) in a list. In the case of all False sum is 0, and in the case of all True sum is equal to the length of the list. any sum value other than 0 & 1 means not all is False or True.


1 Answers

Do you mean something like:

allTrue = all(somePredicate(elem) for elem in someIterable) anyTrue = any(somePredicate(elem) for elem in someIterable) 
like image 147
eumiro Avatar answered Oct 06 '22 01:10

eumiro