Python Anonymous/Lambda Function

Python Anonymous/Lambda Function


In this articles, you’ll learn about the anonymous functions, also known as the lambda functions. You’ll learn what they are, their syntax and how to use them.

1. What are lambda function in Python?

In Python, an anonymous function is a function that is defined without a name.

While normal functions are defined using the def keyword in Python, anonymous function are defined using the lambda keyword.

2. How to use lambda Function in Python?

2.1 Syntax of Lambda Function in Python

lambda arguments: expression

Lamda functions can have any number of arguments but only one expression. The expression is returned.

2.2 Example of Lambda Funuction in Python

double = lambda x: x * 2

print(double(5))

Output:

10

In above program, lambda x: x * 2 is the lambda function. Here x is the argument and x * 2 is the expression that gets returned.

3. Use of Lambda Function in Python

We use lambda functions when we require a nameless function for a short period of time.

In Python, we generally use it as an argument to a high-order function(a function that takes in other functions as arguments). Lambda function are used along with built-in functions like filter(), map() etc.

3.1 Example with filter()

The filter() funciton in Python takes in a function and a list as arguments.

The function is called with all the items in the list and return a new list which contains items for which the function evaluate to True.

e.g.

my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(filter(lambda x: (x%2==0)), mylist)

print(newlist)

Output:

[4, 6, 8, 12]

3.2 Example with map()

The map() funciton in Python takes in a function and a list as arguments.

The function is called with all the items in the list and return a new list which contains items returned by that function for each items.

e.g.

my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = [*map(lambda x: x * 2, my_list)]

print(new_list)

Output:

[2, 10, 8, 12, 16, 22, 6, 24]
上一篇:搞笑但又真实无比! 59条和程序员相关的名人语录,哪一条让你感同身受?


下一篇:FTP漏洞利用