I am trying to find out if there are any built-in tools in Python that work the same way any() and all() are implemented, but instead of checking if each element is truthy or falsy, you can pass your own boolean-evaluating function or lambda, sort of like you can do with the map()
function.
So what I'm asking is if there are any built-in functions where you could do something like:
from random import randint
lst = [randint(1, 100) for _ in range(1000000)]
has_even = any(lambda x: not x % 2, lst)
or
has_even = any(has_even_fn, lst)
where has_even_fn
would be a function that checked if an integer is even.
You can still use any()
to check if lst
has evens:
has_even = any([not x % 2 for x in lst])
But of course this is strictly O(n)
because the entire boolean list has to be built first, while the function I am asking for would only be O(n)
in the worst case, and potentially O(1)
in the best case.