简体   繁体   中英

How to find a first even number in a list

If there is a even number in the list, return the first one, and if there is no even number, return -1. For example like this:

>>> first_even([5, 8, 3, 2])
8
>>> first_even([7, 1])
-1

I have tried some functions that are able to return the first even but no idea the -1. Pls anybody can give me an advice.

You can use next() for this -

def first_even(lst):
    return next((e for e in lst if e%2==0),-1)

Example runs -

>>> def first_even(lst):
...     return next((e for e in lst if e%2==0),-1)
...
>>> first_even([5, 8, 3, 2])
8
>>> first_even([7, 1])
-1

You may use for else

>>> def first_even(x):
    for i in x:
        if i%2 == 0:
            return i
    else:
        return -1
>>> first_even([5, 8, 3, 2])
8
>>> first_even([7, 1])
-1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM