Jotham Candido
Jotham Candido

Reputation: 11

How do I avoid returning None type when an empty list is passed as an argument?

def first_even(items):
    """ (list of int) -> int

    Return the first even number from items. Return -1 if items contains no even numbers.

    >>> first_even([5, 8, 3, 2])
    8
    >>> first_even([7, 1])
    -1
    """
    counter = 0
    for item in items:
        counter = counter + 1
        if item % 2 == 0:
            return item
        elif counter == len(items):
            return -1

Details Details Details Details Details

Upvotes: 0

Views: 639

Answers (2)

jme
jme

Reputation: 20745

I'd suggest a different approach: raise an exception when no even integer is found. Here's an implementation:

def first_even(items):
    """Returns the first even integer in an iterable producing ints.

    Raises
    ------
    ValueError
        If the iterable contains no even integers, or is in fact
        empty.
    """
    for item in items:
        if item % 2 == 0:
            return item
    else:
        raise ValueError('The list contains no even items.')

Why raise an exception? If you use a return value of -1 to signal an error, then using your function becomes tricky in some cases. For example, suppose I want to check if the first even integer in a list is negative:

if first_even([3, -4, 5, 8]) < 0:
    print('The first even integer is negative!')

This will work for that input, but what about:

if first_even([1, 3, 5]) < 0:
    print('The first even integer is negative!')

This will print the message anyways!

Upvotes: 0

Simeon Visser
Simeon Visser

Reputation: 122446

You can also return -1 in that case:

counter = 0
for item in items:
    counter = counter + 1
    if item % 2 == 0:
        return item
    elif counter == len(items):
        return -1
return -1

When items is empty the for loop simply won't return and it'll go directly to the last line which is return -1.

Upvotes: 1

Related Questions