Close
Close

Python Lambda Functions


In Python, we can create functions known as anonymous functions which don't have a name. A lambda function is a type of anonymous function defined using the lambda keyword.

We know that a regular function is defined using the def keyword. A lambda function is defined using the lambda keyword and hence got its name.

But why would we ever use a lambda function?

Suppose you have created a function having a single statement in its body and that function is called at only one place in your program. In this situation, it doesn’t make much sense to create such short functions for one time use. This is where we can use lambda function in place of regular function. We can directly define the lambda function at the place where it is required instead of defining a function separately and then calling it. This will make the code more readable.

Now the question is why would I ever need a function if I need it only one place and it contains only a single statement? There may be cases where a different function needs a function as their input. In those cases, a lambda function would be helpful.

Let’s see what lambda functions are and then you will understand what we are talking about.

We will discuss more use cases and limitations of lambda functions later.

Using lambda Functions in Python


Before learning to create lambda functions, look at the following function.

def identity(x):
    return x + 1

The function identity() has just one statement and it simply returns the parameter that it receives after incrementing it by 1.

This function can be written in the form of a lambda function as shown below.

lambda x: x + 1

This function created using the keyword lambda doesn’t have a name and is called a lambda function. It has one argument x that is passed to the function. It has one expression x + 1 which is evaluated and returned. Thus, this lambda function will receive an argument x, add 1 to it and then return the result.

Now let’s look at the syntax of a lambda function.

Syntax of lambda function


lambda arguments: expression

lambda is a keyword which is used to define lambda functions.

arguments are the same arguments which we pass to regular functions. There can be any number of arguments in lambda functions.

expression is some expression which is evaluated and returned. There can be only one expression in a lambda function.

Now let’s look at some examples of lambda functions.

Examples of lambda function


The following example has a function square() which takes a number and returns the square of that number.

Python3

def square(x):
    return x**2
	
print(square(3))
Output
9

Now suppose this square() function is called at only one place in the program. Then instead of defining and calling it, we can directly define a lambda function at the place where it is called. Let’s see how.

print((lambda x: x**2)(3))
Output
9

In this example, we defined a lambda function, passed a value to it and printed the value returned by the function. 

lambda x: x**2 - In this function, x is the argument and x**2 is the expression. The function receives the argument x, evaluates the expression x**2 and then returns the result of the evaluation.

(3) - The value 3 is passed to the function, or we can say that 3 is the argument passed to the function. The values passed to a lambda function are enclosed within parentheses ( ) and written after the lambda function definition.

Did you notice that the value of the expression is getting returned even without using the return keyword? In lambda functions, the value of the expression always gets returned, so make sure to write the expressions accordingly.

We can also assign the lambda function to a variable so that we can use it anywhere by directly passing the variable name.

square = lambda x: x**2

print(square(3))
Output
9

In this example, the same lambda function is created and assigned to a variable square. The value 3 is passed to the lambda function by writing square(3). (square(3) is the same as writing  (lambda x: x**2)(3))

Look at another example in which a lambda function takes two arguments and returns the sum of the arguments.

print(( lambda x, y: x + y)(3, 2))
Output
5

The lambda function takes two arguments  x and y and then returns the sum of the arguments. Two values 3 and 2 are passed to the lambda function by writing (3, 2) after the function definition. The first value 3 got assigned to x and the second value 2 got assigned to y.

In the next example, the lambda function created is assigned to a variable sum.

sum = lambda x, y: x + y

print(sum(3, 2))
Output
5

lambda Function with no argument


Yes, we can also define lambda functions with no argument.

dummy = lambda: 10

print(dummy())  # prints 10
Output
10

The lambda function dummy takes no argument and returns 10.

lambda Function with default argument


We can pass positional, keyword and default arguments to lambda functions.

sum = lambda x, y=3: x + y

print(sum(3))
print(sum(3, 2))
Output
6
5

The lambda function sum takes one positional argument x and one default argument y. We learned about positional and default arguments in this chapter.

When to Use lambda Functions


Lambda functions are easier to create and get executed somewhat faster than regular functions. Therefore, lambda functions can be used instead of regular functions when the functions have only one expression and are of less complexity. This will be helpful to prevent the situation where separate functions are created for one expression long code, making the code more readable.

Lambda functions can also be used when a function (having only one expression) is passed to another function as its parameter. For example, consider a case where a function named foo() takes another function func() as its parameter, where func() returns True if the value passed to it is greater than 10, and False otherwise.

# defining function func
def func(x):
    '''Returns True if x > 10, otherwise returns False'''
    return x > 10

def foo(y):
    '''Do something here'''
	
foo(func(12))

Here, instead of declaring a separate function func() and calling it for passing it as an argument to the foo() function, we can directly pass a lambda function as the argument as shown below. 

def foo(y):
    '''Do something here'''
	
foo((lambda x: x > 10)(12))

As you can see, this made the code shorter and more clean.

Therefore, lambda functions should be used when the function logic is less complex and can be reduced to a single expression. These are used when the function is not called frequently. In all other scenarios, it is better to use regular functions.

Lambda functions can also be used with built-in functions in Python like filter() and map().

Lambda Function with filter()


The filter() function is used to filter an iterable like list, tuple, dictionary, set, range, etc., based on some condition. For example, it can be used if you want to filter out (remove) all the odd elements of a list.

The filter() function takes two parameters - a function and an iterable.

The function gets called once with each element of the iterable as argument. The filter() function returns only those elements of the iterable for which the function returns True.

To understand this, take the same example in which we have a list and want to keep all the even elements in the list and remove all the odd elements. For that, we will pass a function which returns True if the value passed to it is even and False if it is odd as the first argument and the list to be filtered as the second argument to the filter() function.

Examples


Let’s take an example in which the filter() function filters out the odd elements of a list mylist.

mylist = [5, 7, 8, 10, 14, 15, 20]

def even(num):
    if num % 2 == 0:
        return True
    else:
        return False

new_list = list(filter(even, mylist))
print("Filtered list:", new_list)
Output
Filtered list: [8, 10, 14, 20]

We passed a function even() and a list mylist to the filter() function. The even() function returns True if the value passed to it is even, and returns False otherwise. Internally, each element of the list mylist is passed to the even() function and only those elements for which the function returns True are returned by the filter() function.

Finally, the list() function creates a list with all the even elements returned by the filter() function as its elements.

We can pass a lambda function instead of the regular function to make the code more readable and short. The code for the same is given below.

mylist = [5, 7, 8, 10, 14, 15, 20]

new_list = list(filter(lambda num: num % 2 == 0, mylist))
print("Filtered list:", new_list)
Output
Filtered list: [8, 10, 14, 20]

In the lambda function, the expression num % 2 == 0 returns True if num is divisible by 2, otherwise it returns False.

Let’s see one more example in which we will filter out all the odd numbers from 1 to 10 (included).

myrange = range(1, 11)

new_list = list(filter(lambda num: num % 2 == 0, myrange))
print("Filtered list:", new_list)
Output
Filtered list: [2, 4, 6, 8, 10]

This example is similar to the previous example, with the difference that instead of list, we have passed a range of numbers from 1 to 10 to be filtered.

In the above two examples, instead of defining a new function and calling it inside the filter() function, we have defined a lambda function there itself. This will prevent us from defining and calling a new function every time a filter() function is defined.

Lambda Function with map()


The map() function is used to modify each element of an iterable like list, tuple, dictionary, set, range, etc. For example, it can be used if you want to increase the value of all the elements of a list by 1.

The map() function takes two parameters - a function and an iterable.

The function gets called once with each element of the iterable as an argument and returns the modified element. The map() function returns the iterable having the modified elements.

For example, consider a case when we want to increase the value of each element of a list by 1. For that, we will pass a function which adds 1 to the value passed to it and returns the incremented value as the first argument and the list to be modified as the second argument to the map() function.

Examples


In the following example, each element of the list mylist is multiplied by 2.

mylist = [5, 7, 8, 10, 14, 15, 20]

def multiply(num):
    return num * 2

new_list = list(map(multiply, mylist))
print("Modified list:", new_list)
Output
Modified list: [10, 14, 16, 20, 28, 30, 40]

We passed a function multiply() and the list mylist to the map() function. Internally, the function multiply() takes each element of the list mylist as an argument and returns the element after multiplying it with 2. Finally, the map() function returns the iterable with the modified elements.

Finally, the list() function converts the iterable returned by map() to list.

In the next example, the function multiply() is replaced by a lambda function.

mylist = [5, 7, 8, 10, 14, 15, 20]

new_list = list(map(lambda num: num * 2, mylist))
print("Modified list:", new_list)
Output
Modified list: [10, 14, 16, 20, 28, 30, 40]

Using map() with Multiple Iterables


Suppose a function passed to map() takes two iterable arguments. In that case, we need to pass those iterables separated by comma to map() as well.

list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8, 9, 10]

def add(num1, num2):
    return num1 + num2

new_list = list(map(add, list1, list2))
print("Modified list:", new_list)
Output
Modified list: [7, 9, 11, 13, 15]

In this example, the function add() takes one element of list1 and one element of list2, adds both the elements and returns the result.

First, the function takes the first elements of both the lists, adds them and returns the result. After that, it takes the second elements of both the lists to add them and return the result. This continues till all the elements of the lists are added.

This example is rewritten using a lambda function below.

list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8, 9, 10]

new_list = list(map(lambda num1, num2: num1 + num2, list1, list2))
print("Modified list:", new_list)
Output
Modified list: [7, 9, 11, 13, 15]

The lambda function defined here takes two arguments num1 and num2 and returns the result of num1 + num2.

To learn from simple videos, you can always look at our Python video course on CodesDope Pro. It has over 500 practice questions and over 20 projects.
Following's not really my style.
- Iron Man


Ask Yours
Post Yours
Doubt? Ask question