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.
