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

Python

Python Problem Overview


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

Python Solutions


Solution 1 - Python

Do you mean something like:

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

Solution 2 - Python

allTrue = all(map(predicate, iterable))
anyTrue = any(map(predicate, iterable))

Solution 3 - Python

Here is an example that checks if a list contains all zeros:

x = [0, 0, 0]
all(map(lambda v: v==0, x))
# Evaluates to True

x = [0, 1, 0]
all(map(lambda v: v==0, x))
# Evaluates to False

Alternative you can also do:

all(v == 0 for v in x)

Solution 4 - Python

You can use 'all' and 'any' builtin functions in Python:

all(map(somePredicate, somIterable))

Here somePredicate is a function and all will check if bool() of that element is True.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEnno ShiojiView Question on Stackoverflow
Solution 1 - PythoneumiroView Answer on Stackoverflow
Solution 2 - PythonDon O'DonnellView Answer on Stackoverflow
Solution 3 - PythonRafaelView Answer on Stackoverflow
Solution 4 - PythonRafiView Answer on Stackoverflow