How to Use 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, when 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):
      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 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
>f(1,2)
3

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()

With map function we can apply a lambda function to each element of a list. Here, we are using map and lambda function to get the square of each element in the list my_list. The result is a list with squares of original list.

>map(lambda x: x*2, my_list)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38]

Using lambda function with filter()

With filter function, we can filter a list based on condition specified by a lambda function. For example, here we are filtering the list with condition of element in the list is greater than 10. The result from filter is a smaller list with elements satisfying the condition specified by lambda function.

filter(lambda x: x >10, my_list)
[11, 12, 13, 14, 15, 16, 17, 18, 19]

Using lambda function with reduce()

With reduce function, we can iteratively apply lambda function to reduce the list to a number in this case we use reduce and lambda function to get sum of all the elements in the list.

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