Menu
Scaler Ads

Lambda Function in Python – How and When to use?

Lambda Function, also referred to as ‘Anonymous function’ is same as a regular python function but can be defined without a name.

1. What is Lambda Function in Python?

Lambda Function, also referred to as ‘Anonymous function’ is same as a regular python function but can be defined without a name. While normal functions are defined using the def keyword, anonymous functions are defined using the lambda keyword. However,they are restricted to single line of expression. They can take in mutliple parameters as in regular functions.

2. Lambda Function Syntax

The syntax for lambda function is given by : lambda arguments: expression Notice, there can be any number of arguments but can contain only a single expression. There is no return statement which is usually present in the def function syntax. The function will simply return the expression value even when there is no return statement.

Contents

3. Need for Lambda Functions

There are at least 3 reasons:

    1. Lambda functions reduce the number of lines of code when compared to normal python function defined using def keyword. But this is not exactly true because, even functions defined with def can be defined in one single line. But generally, def functions are written in more than 1 line.
    2. They are generally used when a function is needed temporarily for a short period of time, often to be used inside another function such as filter, map and reduce.
    3. Using lambda function, you can define a function and call it immediately at the end of definition. This can’t be done with def functions.

Let’s see more about implementation of them in python.

4. How to use lambda functions: Simple Example

You don’t need to specify a name for the function as discussed above about the syntax of lambda function. Let’s try to define a function for calculating the squares of given values.

# calculate squares using lambda
squares = lambda x: x*x
print('Using lambda: ', squares(5))
Using lambda:  25

Let’s also look at how to do the same function using def keyword, and compare them.

# calculate squares using def
def squares_def(x):
    return x*x
print('Using def: ', squares_def(5))

Output:

Using def:  25

Do the same in a single line.

# calculate squares using def in one line
def squares_def(x): return x*x

print('Using def: ', squares_def(5))
Using def:  25

See that while using the def keyword, we are returning a certain value x*x . In the case of lambda function, the expression x*xwill be returned without writing an explicit return statement. Generally in normal use, there is not much of a difference in using def and lambda keyword. Both of them are in fact functions. Let’s see their types.

# Types
print(type(squares))
print(type(squares_def))
<class 'function'>
<class 'function'>

Both of them belong to the class function.

5. Internally, both lambda and def functions works exactly the same

To check how they work internally, use the dis keyword. dis keyword will expose a readable version of python bytecode allowing inspection of instructions.

# Bytecode instructions of lambda function
import dis
dis.dis(squares)
  2           0 LOAD_FAST                0 (x)
              2 LOAD_FAST                0 (x)
              4 BINARY_MULTIPLY
              6 RETURN_VALUE

Bytecode for regular `def` function.

# Bytecode instructions of def function
import dis
dis.dis(squares_def)
  2           0 LOAD_FAST                0 (x)
              2 LOAD_FAST                0 (x)
              4 BINARY_MULTIPLY
              6 RETURN_VALUE

See that the process undertaken by both the functions are exactly the same. So, there is no real difference in the way they execute.  

6. Lambda functions can have 0 or 1 expression, not more.

  1. No expression : contains no expression, will give the same output for all arguments.
x = lambda : "hello world"
print(x())

Output:

hello world
  1. Single expression: They can contain either one expression or no expression. We cannot put more than one expression in a lambda function.
new_single = lambda x : (x%2)
print(new_single(10))
0

7. Lambda functions can be Immediately Invoked

You can implement a lambda function without using a variable name. You can also directly pass the argument values into the lambda function right after defining it using paranthesis. This cannot be done using def functions.

(lambda x,y : x*y)(5,7)
#> 7

This doesn’t work with def function.

# Doesn't work with def
def multiply(x, y): return x*y (5,7)

8. It is possible to write higher order functions using lambda

A lambda function can take another function as an argument. Let’s look at an example of a nested lambda functions, a lambda function inside another lambda function.

# Define a lambda function that can take another lambda function (func1). 
high_order = lambda x, lmbfunc: x*lmbfunc(x)

# The inner lambda function is defined when calling the high_order.
high_order(10, lambda x : x*x)
#> 1000

See that I have passed another lambda function to calculate the square as argument to the variable high_order func.

9. Lambda functions accept all kinds of arguments, just like normal def function

lambda function supports all kinds of arguments just like the normal def function. 1. Keyword Arguments: keyword argument is an argument preceded by an identifier (e.g. name=) in a function call. Named Arguments: Example

(lambda x, y=3, z=5: x*y*z)(7)
#> 105

Variable list of Arguments: Example

(lambda x, y=3, z=5: x*y*z)(x=7)
#> 105

Variable list of keyword arguments: Example

(lambda *args : sum(args))(3,5,7)
#> 15

2. Positional arguments: positional argument is an argument that is not a keyword argument.

(lambda x,y,z : x*y*z)(3,5,7)
#> 105

10. You can use lambda function in filter()

filter() function is used to filter a given iterable (list like object) using another function that defines the filtering logic. A lambda function is typically used to define the filtering logic and is passed as the first argument of filter(). An iterable like a list object is passed as the second argument to the filter function.

# Using lambda inside filter function
mylist = [2,3,4,5,6,7,8,9,10]
list_new  = list(filter(lambda x : (x%2==0), mylist))
print(list_new)
#> [2, 4, 6, 8, 10]

11. You can use lambda function in map()

map() function applies a given function to all the itmes in a list and returns the result. Similar to filter(), simply pass the lambda function and the list (or any iterable, like tuple) as arguments.

# using lambda inside map function
mylist = [2,3,4,5,6,7,8,9,10]
list_new  = list(map(lambda x : x%2, mylist))
print(list_new)
#> [0, 1, 0, 1, 0, 1, 0, 1, 0]

12. You can use lambda function in reduce() as well

reduce() function performs a repetitive operation over the pairs of the elements in the list. Pass the lambda function and the list as arguments to the reduce() function. For using the reduce() function, you need to import reduce from functools librray.

# Using lambda inside reduce
from functools import reduce
list1 = [1,2,3,4,5,6,7,8,9]
sum = reduce((lambda x,y: x+y), list1)
print(sum)
#> 45

See that the reduce() function iteratively multiplies over the elements in the list . i.e 1+2, 1+2+3 , 1+2+3+4 and so on.

13. How to use lambda function to manipulate a Dataframe

You can also manipulate the columns of the dataframe using the lambda function. It’s a great candidate to use inside the apply method of a dataframe. I will be trying to add a new row in the dataframe in this section as example.

import pandas as pd
df = pd.DataFrame([[1,2,3],[4,5,6]],columns = ['First','Second','Third'])
df['Forth']= df.apply(lambda row: row['First']*row['Second']* row['Third'], axis=1)
df
  First Second Third Forth
0 1 2 3 6
1 4 5 6 120

When used with df.appplymap() it applies the lambda function to every element of the dataframe.

df = df.applymap(lambda x: x*x)
df
  First Second Third Forth
0 1 4 9 36
1 16 25 36 14400

Conclusion

Hope you are clear with what lambda functions are and how you can use it in various situations. Try out the following exercises to test your understanding:

  1. Compute factorial of 10 using lambda function. Hint: Use reduce.
  2. Write a function to filter all multiples of 2 and 3 from the list: [1,2,3,4,5,6,7,8,9,10,11,12]

Course Preview

Machine Learning A-Z™: Hands-On Python & R In Data Science

Free Sample Videos:

Machine Learning A-Z™: Hands-On Python & R In Data Science

Machine Learning A-Z™: Hands-On Python & R In Data Science

Machine Learning A-Z™: Hands-On Python & R In Data Science

Machine Learning A-Z™: Hands-On Python & R In Data Science

Machine Learning A-Z™: Hands-On Python & R In Data Science