Explore Lambda Functions
00:00 A lambda function, or an anonymous function, is a function that doesn’t have a name. It can take any number of arguments, but can only have one expression.
00:11 This means that you can get several input arguments, but you cannot have multiple variables to be returned directly from the lambda function. It’s used when you need a quick function for a short period of time and don’t want to define a separate function for it.
00:27
Lambda functions are defined using the lambda
keyword and are commonly used as another function’s argument. You can see an example here. It’s a lambda function that doubles a number, lambda x:
x * 2
. So you start with the lambda
keyword, then specify your input, which is x
here.
00:49
Then you put a colon and type what you want to do with your input. In this case, it’s x * 2
, which means you’re doubling your input. In the next lessons, you’ll learn all about functions like map()
and reduce()
that often take lambda functions as their argument.
01:07
And if you’re wondering whether you need to import anything to use the lambda
keyboard, the answer is no. The lambda
keyboard is built in and readily available for use.
01:19
Let’s do a quick example. Let’s take two numbers and add them together. Before writing up the lambda function, let’s create a regular function that does this. def add_numbers()
taking num1
and num2
as input … and return
. We want to add them together, so num1 + num2
.
01:46
Now let’s write up the lambda function. add = lambda
. Then your input arguments go here, num1
, num2
, and colon. What do you want to do with them?
01:59
You want to add them together, so num1 + num2
.
02:06
Now add
here is a function object. Let’s use it to add 2
and 3
together. add(2, 3)
. The result is 5
, which is, well, two plus three.
02:21
You could also directly plug in 2
and 3
. Let’s do that now. result =
… So you’re using the same lambda function here as before, but just you’re putting it into a parentheses. (lambda num1, num2: num1 + num2)
.
02:40
And you’re plugging in 2
and 3
, so (2, 3)
.
02:49
Now let’s call result
, and you get 5
again, which is two plus three.
02:56
To summarize what you just learned, lambda functions are nameless functions that you use when you need a function for a short period of time. They use the lambda
keyword and are often used as other functions’ arguments, like reduce()
and map()
, which you’ll learn about in the next lessons.
Become a Member to join the conversation.