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 lambda.

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.

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.

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() & Lambda Function

The 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.

Printing 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 Lambda Function

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 word1.

We will convert the above simple function into a lambda function.

In the following example, we will:

  • Define a lambda function echo_word using the variables word1 &echo. Replicate what the original function definition for echo_word() does above.
  • Call echo_word() with the string argument 'hey' & the value 5, in that order. Assign the call to result. Finally, print the result variable.

When we run the above code, it produces the following result:

RELATED LINKS:

Data Scientist & Machine Learning Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store