Join us and get access to thousands of tutorials and a community of expert Pythonistas.
This lesson is for members only.Join us and get access to thousands of tutorials and a community of expert Pythonistas.
Explore Lambda Functions
00:00A lambda function, or an anonymous function, is a function that doesn’t have aname. It can take any number of arguments, but can only have one expression.
00:11This means that you can get several input arguments,but you cannot have multiple variables to be returned directly from the lambdafunction.It’s used when you need a quick function for a short period of time and don’twant to define a separate function for it.
00:27Lambda functions are defined using thelambda keyword and are commonlyused 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 thelambda keyword,then specify your input, which isx here.
00:49Then you put a colon and type what you want to do with your input. In this case,it’sx * 2, which means you’re doubling your input.In the next lessons,you’ll learn all about functions likemap() andreduce() that often take lambdafunctions as their argument.
01:07And if you’re wondering whether you need to import anything to use thelambdakeyboard, the answer is no.Thelambda keyboard is built in and readily available for use.
01:19Let’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()takingnum1 andnum2 as input …andreturn. We want to add them together,sonum1 + num2.
01:46Now 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:59You want to add them together, sonum1 + num2.
02:06Nowadd here is a function object.Let’s use it to add2 and3 together.add(2, 3). Theresult is5, which is, well, two plus three.
02:21You could also directly plug in2 and3. 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:40And you’re plugging in2 and3,so(2, 3).
02:49Now let’s callresult, and you get5 again,which is two plus three.
02:56To summarize what you just learned,lambda functions are nameless functions that you use when you need a functionfor a short period of time.They use thelambda keyword and are often used as other functions’arguments, likereduce() andmap(), which you’ll learn about in the next lessons.
Course Contents
- Get Started With filter()
- Use filter() for Functional Programming
- Code With Pythonic Style

