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, reduce 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 my_add(a,b):

The above very simple function is your own version of a function to add two variables and one can call it as my_add(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 can 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.

Although typically lambda function is used anonymously, one can assign it to a variable and use the function with the variable name. For example, we can

>f = lambda a, b: a+b

The benefit of lambda functions are easily visible when used with python functions map, filter, and reduce.

>my_list = range(20)

Using lambda function with map()

>map(lambda x: x*2, my_list)

Using lambda function with filter()

>filter(lambda x: x >10, my_list)

Using lambda function with reduce()

>reduce(lambda x, y: x+y, my_list)