You can write your very own Python functions using the def keyword, function headers, docstrings, and function bodies. However, there's a quicker way to write functions on the fly, and these are called lambda functions because you use the keyword lambda.
Some function definitions are simple enough that they can be converted to a lambda function. By doing this, you write fewer lines of code, which is pretty awesome and will come in handy, especially when you're writing and maintaining big programs.
lambda Function
Here we rewrite our function raise_to_power as a lambda function. After the keyword lambda, we specify the names of the arguments; then, we use a colon followed by the expression that specifies what we wish the function to return.
raise_to_power = lambda x, y: x ** y
raise_to_power(2, 3)
As mentioned, the lambda functions allow you to write functions in a quick and dirty way, so we wouldn't advise you to use them all the time, but there are situations when they come in handy, like the example below.
map() and lambda Function
The map function takes two arguments, a function and a sequence such as a list and applies the function over all the elements of the sequence. We can pass lambda function to the map without even naming them, and in this case, we refer to them as anonymous functions.
In this example, we use map() on the lambda function, which squares all elements of the list, and we store the result in square_all.
nums = [48, 6, 9, 21, 1]
square_all = map(lambda num: num ** 2, nums)
print(square_all)
You can write your very own Python functions using the def keyword, function headers, docstrings, and function bodies. However, there's a quicker way to write functions on the fly, and these are called
lambdafunctions because you use the keywordlambda.Some function definitions are simple enough that they can be converted to a lambda function. By doing this, you write fewer lines of code, which is pretty awesome and will come in handy, especially when you're writing and maintaining big programs.
lambdaFunctionHere we rewrite our function
raise_to_poweras a lambda function. After the keywordlambda, we specify the names of the arguments; then, we use a colon followed by the expression that specifies what we wish the function to return.As mentioned, the
lambdafunctions allow you to write functions in a quick and dirty way, so we wouldn't advise you to use them all the time, but there are situations when they come in handy, like the example below.map()andlambdaFunctionThe
mapfunction takes two arguments, a function and a sequence such as a list and applies the function over all the elements of the sequence. We can passlambdafunction to themapwithout even naming them, and in this case, we refer to them as anonymous functions.In this example, we use
map()on thelambdafunction, which squares all elements of the list, and we store the result insquare_all.