Search code examples
pythonfunctionfor-loopreturn

Explain how python execute this function?


def check_even_list(num_list):
    # Go through each number
    for number in num_list:
        # Once we get a "hit" on an even number, we return True
        if number % 2 == 0:
            return True
        else:
            return False

now when execute function

[1]-check_even_list([1,2,3]) 
False 

[2]-check_even_list([2,1,3]) 
True 

why this True when #3 is return False ???

[3]-check_even_list([1,4,2]) 
False 

Why this False when #2 is return True ???


Solution

  • You are using "early return statements". What your function does is actually only evaluating the first element of your list.

    Here's I would write the function:

    def check_even_list(num_list):
        return all(map(lambda x: x % 2 == 0, num_list))