Getting Started with Lambda Functions in Python



Python lets you create a function on the go, but without really assigning a name to the function. These anonymous functions are called “Lambda Functions”. One typically writes a lambda function on the fly, if one wants to write a function for one-time use. Lambda Functions come handy in a variety of situations and are of great use in the Python’s built-in functional commands like Map and Filter. Let us first understand the basics of Lambda Functions.

Ordinarily, if one wants to write a function in Python, we define and write it as follows.

def myAdd(a,b):
      return(a+b)

The above very simple function is your own version of a function to add two variables and one can call it as myAdd(1,3) anytime. One can also write a lambda function to add two variables.

lambda a, b: a+b

One can see that the lambda function is pretty similar to the regular function except that it does not have a name, “def” to define a function and no return statements. The lambda function is written in a single line. One can assign a lambda function to a variable and use it later. For example, we can assign the lambda function to add two numbers to a variable “plus” and use plus(a,b) to execute the lambda function.

The power of lambda function be realized only when it is used as part of another function. In combination with Python’s built-in functional programming commands, the lambda functions will be of great use.