Given a list of integers such as integers = [1, 2, 3, 4, 5, 6]
I would like to know if there is an even number in the list using Python's any() function. My question is if it is more efficient to pass a list comprehension outcome like so:
evens = [each for each in integers if each % 2 == 0]
has_even = any(evens)
versus using a generator such as:
has_even = any(each for each in integers if each % 2 == 0)
It's better to pass a generator than a list comprehension to any and all. Both of those functions can short-circuit, i.e., any will stop as soon as it encounters a True value, and all will stop as soon as it encounters a False value. If you pass them a list comprehension the whole list has to be built before any / all can start work, but if you pass them a generator then only the needed vales will be generated. So not only do you save RAM using a generator, you may save a substantial amount of execution time, too.
Your generator can be made more efficient; the if part is redundant.
has_even = any(each % 2 == 0 for each in integers)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With