Charles Dong
Charles Dong

Reputation: 61

How to check if there's any odd/even numbers in an Iterable (e.g. list/tuple)?

Suppose we're checking if there's any odd numbers in a list. The most direct way is:

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

The has_odd function checks if there's any odd numbers in a list, once an odd number is found, it returns True. But this seems a bit verbose. A more concise way using reduce is as follow:

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

But this will iterate through all elements and is unnecessary, because once an odd number is found the result is surely True.

So, are there any other ways to do this?

Upvotes: 5

Views: 5324

Answers (3)

R.A.Munna
R.A.Munna

Reputation: 1709

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

Upvotes: 0

Azat Ibrakov
Azat Ibrakov

Reputation: 11009

first of all let's write small indicator function for "oddness" like

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 with 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

Upvotes: 1

Chris
Chris

Reputation: 22993

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

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

Note however, any() is pretty much the same as you had originally just generalized, so don't expect a speed improvement:

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

Upvotes: 6

Related Questions