Introduction

Lambda function in Python are the anonymous function that means that the function has the anonymous name. As we already know, a standard Python function is defined using the def keyword. Similar to this, Python uses the lambda keyword to define an anonymous function.

Syntax

Below is the syntax used for defining the lambda function:

lambda arguments: expression

  • There is only one expression that is evaluated and returned in this function, regardless of the number of parameters.
  • Lambda functions can be used anywhere that function objects are required.
  • The fact that lambda functions are syntactically limited to a single expression must always be kept in mind.
  • In addition to several kinds of expressions in functions, it has a variety of purposes in specific programming disciplines.

Example

Now, we know some basics about the lambda function in python, lets see a basic example of how it works. In this example, we are just reversing the string.

str1 = 'Board Infinity'


revstr = lambda string: string[::-1]

print(revstr(str1))

Output:

ytinifnI draoB

Difference between lambda function and def keyword:

Lamba Function

Def Keyword

Good for performing short operations.

Good for cases where multiple lines of code is needed.

Using lambda function can reduce the reusabillty of code

Code reusability is increased and multiple comments are used.

supports statements with a single line and a return value.

supports a function block with any number of lines.

Some examples of Python Lambda Function

Example 1: Python lambda function with list comprehension.

In this example, we will be using lambda function for making lists.

simple_list = [lambda arg=x: arg for x in range(1, 11)]


for item in simple_list:

print(item())

Output:

1

2

3

4

5

6

7

8

9

10

write your code here: Coding Playground

Example 2: Python lambda function with if-else.

In this example, we will be using lambda function with if-else to find the minimum of two numbers.

min = lambda a, b : a if(a < b) else b


print(min(4, 12))

Output:

4

write your code here: Coding Playground

Example 3: Using lambda() function with filter().

In this example, we will be filter out all the even numbers from the list.

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


filtered_list = list(filter(lambda x: (x % 2 != 1), l))

print(filtered_list)

Output:

[2, 4, 6, 8, 10]

write your code here: Coding Playground

Example 4: Using lambda() function with map().

In this example, we will be using map to update all the aray elements.

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


final_list = list(map(lambda x: x+10, l))

print(final_list)

Output:

[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

write your code here: Coding Playground