How to check if there are even / even numbers in Iterable (e.g. list / tuple)?

Suppose we check for any odd numbers in list . The most direct way:

 def has_odd(L): for v in L: if v % 2 == 1: return True return False 

The has_odd function checks for any odd numbers in list , once an odd number is found, it returns True . But that seems a bit verbose. A more concise way to use reduce is as follows:

 reduce(lambda res, v: res or bool(v), L, False) 

But it will be an iteration over all elements and is not needed, because as soon as an odd number is found, the result is certainly True .

So, are there other ways to do this?

+5
source share
3 answers

You can use the any() function to reduce verbosity:

 >>> l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> any(n % 2 == 1 for n in l) True >>> 

Note, however, any() almost the same as you originally just generalized , so don't expect speed improvements:

 def any(iterable): for element in iterable: if element: return True return False 
+6
source

first of all write a small indicator function for "oddness", for example,

 def is_odd(number): return number % 2 

then we can write our indicator for โ€œhas at least one odd numberโ€ using any with imap / map

  • Python 2 ..

     from itertools import imap def has_odd_number(iterable): return any(imap(is_odd, iterable)) 
  • Python 3. *

     def has_odd_number(iterable): return any(map(is_odd, iterable)) 

or generator expression

 def has_odd_number(iterable): return any(is_odd(number) for number in iterable) 

Examples:

 >>> has_odd_number([0]) False >>> has_odd_number([1]) True 
+1
source

Another way. you can use not all()

 >>> l = [2, 4, 5, 6, 7, 8, 9, 10] >>> not all(n%2==1 for n in l) True 
0
source

Source: https://habr.com/ru/post/1268347/


All Articles