2

I tried 2 snippets to figure out the difference between python lambda and regular function.

this one get what is expected.

b = range(6)
def greater_than2(b):
    if b > 2:
        return b

print(list(filter(lambda x: x > 2, b)))
print(list(filter(greater_than2, b)))

both print give [3, 4, 5].

but something goes with this one

b = range(6)

def less_than2(b):
    if b < 2:
        return b

print(list(filter(lambda x: x < 2, b)))
print(list(filter(less_than2, b)))

i got following output

[0, 1]
[1]

so, what the difference between the lambda and less_than2 function?

1
  • 3
    Your functions should be returning true or false, not b. When b is zero, less_than2(b) returns 0, which is a falsey value. Commented Oct 30, 2018 at 14:41

1 Answer 1

3

Your functions are not comparable, greater_than2 needs to return a Boolean:

def greater_than2(b):
    return b > 2

The function defined above will return True when b > 2, or False when b <= 2.

Your regular functions return b. Let's consider what happens with your second example, where you see a discrepancy:

b = 0: less_than2 returns 0
b = 1: less_than2 returns 1
b = 2: less_than2 returns None
...
b = 5: less_than2 returns None

Notice if your if condition is not satisfied, a return statement is never met and therefore your function will return None. The only "Truthy" value of these return values is 1 as bool(0) and bool(None) evaluate to False.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.