Amit Dhanuka
Amit Dhanuka

Reputation: 53

filter function is giving different result for functions & lambda expressions, Why?

I am trying to filter even numbers from a list by using filter function of Python

def evenNum(num):
    if num % 2 == 0 :
        return num

list1 = [i for i in range(-10 , 10)]

print (list1)
# [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(list(filter(evenNum,list1)))
# [-10, -8, -6, -4, -2, 2, 4, 6, 8]

print(list(filter(lambda x: x % 2 == 0 , list1)))
# [-10, -8, -6, -4, -2, 0, 2, 4, 6, 8]

Why 0 is missing when an defined function is used?

Upvotes: 0

Views: 200

Answers (3)

aikikode
aikikode

Reputation: 436

Because filter leaves only those elements for which the provided method returns True. Your method:

def evenNum(num):
    if num % 2 == 0 :
        return num

Does not return bool, but either None which is translated to False or num which is also translated to bool(num). And bool(0) == False, so your filter method won't pass 0. You need to modify it to return bool value:

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

Upvotes: 6

brunns
brunns

Reputation: 2764

Your function returns the number if it's even. Otherwise, it returns None.

Your lambda returns True if the number is even, False otherwise.

If you filter on what's returned by each of these, your function will exclude 0, because 0 evaluates as false. The lambda will return True for 0, so it will be included.

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 600059

Your functions don't return the same thing. Your lambda correctly returns a boolean. But your other function returns the number itself; and 0 is boolean False.

To get the correct result you should return a bool:

def evenNum(num):
    if num % 2 == 0 :
        return True

Upvotes: 3

Related Questions