In this video, we're going to look at how to use the Lambda Function in Python
Video Transcription
Hi, my name is Art, and I teach Python at Noble Desktop. In this video, I'll explain how to use Lambda in Python. So, first of all, what is Lambda? Lambda is an anonymous function, meaning it has no name. Some people say that the syntax is too complicated, but in this video, I'll show you how easy it is to use Lambda.
As I said, Lambda is an anonymous function, but let's begin with a plain vanilla Python function. So, what is a function? A function is a block of reusable code. The key word here is reusable, so if you want to use something over and over again, you compose a function. Now, let's create a simple function. I'm going to begin with the keyword "def" (stands for defined).
I'm going to come up with some kind of name, let's say "add", and here I'm gonna pass two arguments into my function, using arguments "a" and "b". Pretty simple so far, right? And, a function takes arguments and returns the result. So here we need to use a return operator, and what we want to do is add "a" and "b". That's my function, pretty simple so far.
So, we could call this function, or we could say invoke this function with two arguments, let's say "five" and "six", and we get "11". Pretty pretty simple now. What I'm going to do next is rewrite this function using a Lambda expression.
So, what I'm going to do next is use the Lambda keyword. To be consistent, I'm just going to copy "a" and "b" that I used here and place them here. And then, pretty much like here, you see the same stuff.
Now, the only difference is we're not going to be using the return operator, because the return is built in to the Lambda. So, all we have to do is pass an expression; in this case, our expression is "a + b". So, I'm just going to copy "a + b" and place it here, and that's it, that's my Lambda.
The main thing to remember is that you cannot use Lambda by itself, so Lambda should be used within some helper functions, such as "function", "map", or "sorted". Now, we're going to assign it to a variable name, randomly picking the variable name "f". Now, I could call this variable name with two arguments, "five" and "six", and then expression. So, one more time, you always begin with the keyword "Lambda", then you define the variable name or names, and then an expression. That's it!
And you might ask, what's the difference? The difference is when you use "def", Python will store this as an object, it will be sitting in your Python memory. So, if you want to use this function over and over again, you better wrap it as a function. However, if you want to do something on the fly, especially when you do some data cleaning or data manipulation, you can use Lambda, because Lambda runs as an expression.
And that's it, that's the whole Lambda. Watch my other videos to learn more.