Your First Lambda Functions
In this lesson, you’re going to see some code created in the Python REPL, where you can create your first lambda functions. You’ll try a few lambda functions yourself in order to square a number, add two numbers together, and multiply three numbers.
You’ll also take a quick look at using default values. It’s also possible to assign default values for the variable. This can make your lambda expressions more convenient to use.
00:00 Your first lambda functions. Here you’ll see some code created in the Python REPL, where you can create your first lambda functions. First up, squaring a number.
00:17 So now to see lambda functions in action, we’re going to make use of the Python shell. We’ll create them interactively. Despite them often being known as anonymous functions, we will actually assign them to variables.
00:31
We’ll give them names to allow us to access them and send different values into them. The first one I’m going to create will just be called squared
.
00:42
It starts off with the keyword lambda
. lambda x:
and all it will return is x
to the power of 2
. Now if we make use of squared()
, we can pass in any number, and get our result back. There you go—your first lambda function.
01:15
In many cases, people use the variable x
as the variable for lambda
, but you can actually use any variable name you want. So just as a quick demonstration, we could redefine squared()
with exactly the same mechanics, and it will work in exactly the same way.
01:42
Next up, adding two numbers together. Lambda expressions can take more than one input, so here we’ll see simple addition done with a lambda expression using the variables x
and y
.
02:02
It will simply return x + y
. Now we can use that to add two numbers together, and you can see it works perfectly.
02:23 Next, multiplying three numbers. Of course, you aren’t limited to two variables. Here we’ll create one where there are three numbers which are multiplied together.
02:47
Finally, a quick look for using default values. It’s also possible to assign default values for the variables. This can make your lambda expression more convenient to use. So, going back to our first example squared()
, we could make a more general purpose power()
function.
03:11
It can have a default value for the exponent, in this case 2
, which we can replace with a parameter if we want to. So here, we could do 5
to the power of 3
, but if we just wanted 5
squared, we only need to input one value, as the default of 2
for y
will be used.
Become a Member to join the conversation.