lambda-function
Roy Lv7

Python: What is a Lambda Function?

In Python ,the lambda keyword is used to define an anonymous(i.e.,nameless) function, using the follow syntax:

lambda parameters: expression

Assunme we have the follow list of fruits:

fruits = ['apple','orange','grape','lemon','mango','banana']

Now imagine we need to filter our list to print only fruit names which are 5 characters long.We could do so by defining a named function to test word lengths,and then passing it (and our list of fruits) to filter():

1
2
3
4
5
6
7
def five_letter_words(word):
if len(word) == 5:
return True
five_letter_fruits = filter(five_letter_words,fruits)

for fruit in five_letter_fruits:
print(fruit)

Or, the same task can be accomeplished directly in filter() using lambda expression, without needing to define a separate named function:

1
2
3
five_letter_fruits = filter(lambda word:len(word)==5,fruits)
for fruit in five_letter_fruits:
print(fruit)

Beacuse lambda functions are Python expressions, they can be assigned to variables.
So, this:

1
2
add_two = lambda x,y x+y
add_two(3,5)

Is equivalent to this:

1
2
3
def add_two(x,y):
return x+y
add_two(3,5)
  • 本文标题:lambda-function
  • 本文作者:Roy
  • 创建时间:2020-05-16 10:40:18
  • 本文链接:https://www.yrzdm.com/2020/05/16/lambda-function/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!