Enno Shioji Enno Shioji - 26 days ago 17
Python Question

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

pretty sure there is a common idiom but couldn't find it with google..

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);

Answer

Do you mean something like:

allTrue = all(somePredicate(elem) for elem in someIterable)
anyTrue = any(somePredicate(elem) for elem in someIterable)