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]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值