We can write our very own Python functions using the def keyword, function headers, docstrings, & function bodies. However, there’s a quicker way to write functions on the fly, & these are called
lambda functions because we use the keyword
Some function definitions are simple enough that they can be converted to a lambda function. By doing this, we write fewer lines of code, which is pretty awesome & will come in handy, especially when we’re writing & maintaining big programs.
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.
As mentioned, the
lambda functions allow us to write functions in a quick & dirty way, so I wouldn’t advise you to use them all the time, but there are situations when they come in handy, like the example below.
Map() & L
map function takes two arguments, a function and a sequence such as a list & applies the function over all the elements of the sequence. We can pass
lambda function to the
mapwithout even naming them, & 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, & we store the result in
square_all reveals that its a
map object, so to see what it returns, we use list to turn it into a list & print the result.
Interactive Example of Writing a L
The below function
echo_word takes 2 parameters: a string value,
word1, & an integer value
echo. It returns a string that is a concatenation of
echo copies of
We will convert the above simple function into a lambda function.
In the following example, we will:
- Define a lambda function
echo_wordusing the variables
echo. Replicate what the original function definition for
echo_word()with the string argument
'hey'& the value
5, in that order. Assign the call to
result. Finally, print the
When we run the above code, it produces the following result:
How to Use Python Lambda Functions - Real Python
Take the Quiz " Lambda expressions in Python and other programming languages have their roots in lambda calculus, a…
Python Lambda (Anonymous) Function
In Python, an anonymous function is a function that is defined without a name. While normal functions are defined using…