Home > Mobile >  The Function is breaking before providing all values
The Function is breaking before providing all values

Time:10-12

def list_num_checker(num_list):
    for x in num_list:
        if x%2==0:
            return x 
        else:
            continue

I just began learning Python and this is the code I have written to create a function to return all the even values in a list. However, It breaks down after checking the first even number.E.g.

list_num_checker([1,2,3,4,5,6])
2

Any and all help is appreciated.

CodePudding user response:

return will cause a function to exit... if you use yield you can make it a generator

def list_num_checker(num_list):
    for x in num_list:
        if x%2==0:
            yield x # yield makes this a generator instead
        # else: # you don need the else
        #    continue

for evennum in list_num_checker([1,2,3,4,5,6,7,8]):
    print(evennum)

you could also make a list comprehension

print([x for x in num_list if x%2 == 0])

or you could use the builtin filter function

def is_even(num):
    return num % 2 == 0

list(filter(is_even,num_list)) # its a generator so you need to call list on it

CodePudding user response:

I think you can use yield instead of return since return will break the for loop and immediately returns the give value

def list_num_checker(num_list):
    for x in num_list:
        if x%2==0:
            yield x
        else:
            continue

divisible2 = list(list_num_checker([1,2,3,4,5,6]))

Some possible alternative approaches would be to use list comprehension or filter

def list_num_checker(num_list):
    return [x for x in num_list if x % 2 == 0]
def list_num_checker(num_list):
    return filter(lambda x: x % 2 == 0, num_list)

CodePudding user response:

return will immediately terminate the function. To produce multiple values in one function, use yield instead.

def list_num_checker(num_list):
    for x in num_list:
        if x%2==0:
            yield x 
        else:
            continue
  • Related