How do lambdas work?


#1

Hi,

Im on the "Advanced topics in python" section and have reached lesson 12 but cant wrap my head around it. The lesson tells me that
lambda x: x % 3 == 0
is the same as
def by_three(x):
return x % 3 == 0

but how can the lambda return a value if it the variable "x" hasnt been defined?

Also, how do you return "x % 3 == 0" in the first place? Ive only used the "==" operator in if statements before and never as a functions output.


#2

Hi, @blaablaaguy ,

In this lambda ...

lambda x: x % 3 == 0

... x is the parameter. When calling this anonymous function, we need to pass one argument to it, and that is how x gets a value.

Here ...

return x % 3 == 0

... return is followed by the expression x % 3 == 0. It is not the expression itself that gets returned; rather, the expression evaluates to either True or False, and that value is what gets returned.


#3

Sorry, but i still dont understand. In the example, x isnt given a value. Or am i missing something?

EDIT: If i was to pass an argument to a lambda, where would it go?


#4

@blaablaaguy ,

A function is an object, as is any other type, such as an int or a list. We can pass objects to functions, even when the object is another function.

Here, we are passing two objects to the filter function ...

print filter(lambda x: x % 3 == 0, my_list)

The first object in the argument list is the lambda, which is a function object.

The second object in the argument list is a list of ints.

The filter function calls the function that you supply as the first argument on each item in the list that you supply as the second argument. If the function that you supplied returns True, the item is added to a list that will ultimately be returned by filter. But if the function that you supplied returns False, that item is not added to the list that will ultimately be returned by filter.

So, even though you did not call the lambda function directly, the filter function called it multiple times, passing it one item at a time from my_list.

Here's an example of our calling a lambda directly, although it is more illustrative than useful ...

n = 9
if (lambda x: x % 3 == 0)(n):
    print "{:d} is divisible by 3".format(n)
else:
    print "{:d} is not divisible by 3".format(n)
n = 10
if (lambda x: x % 3 == 0)(n):
    print "{:d} is divisible by 3".format(n)
else:
    print "{:d} is not divisible by 3".format(n)

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.