Python Anonymous/Lambda Function
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python Anonymous/Lambda Function,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2183字,纯文字阅读大概需要4分钟。
内容图文
![Python Anonymous/Lambda Function](/upload/InfoBanner/zyjiaocheng/611/a7f64030519c420898c3438a1eccc7f7.jpg)
Python Anonymous/Lambda Function
- 1. What are lambda function in Python?
- 2. How to use lambda Function in Python?
- 3. Use of Lambda Function in Python
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]
内容总结
以上是互联网集市为您收集整理的Python Anonymous/Lambda Function全部内容,希望文章能够帮你解决Python Anonymous/Lambda Function所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。