-
Overview
What is an anonymous function/method or lambda?
-
Anonymous function
An
anonymous method
is a method without a name, i.e. not bound to an identifier like when we define a method usingdef method:
.Anonymous functions are often arguments being passed to higher-order functions, or used for constructing the result of a higher-order function that needs to return a function.
-
Lambda
From [2], lambda comes from Lambda Calculus and refers to anonymous functions in programming.
Lambda Calculus is a formal system in mathematical logic for expressing computation based on function abstraction and application using variable binding and substitution.
It allows you to write quick throw away functions without naming them.
lambda arguments: expression # def method def add(x, y): return x + y # lambda method lambda x, y: x + y
lambdas differ from Python methods because:
- they can have only one expression, can’t contain any statements
- their return type is a
function object
-
Anonymous method vs. Lambda
Though most people use the term “anonymous function” and “lambda function” interchangeably - they’re not the same.
This mistake happens because in most programming languages lambdas are anonymous and all anonymous functions are lambdas. This is also the case in Python.
-
Why are lambda relevant to
map()
,filter()
,reduce()
?All three of these methods expect a
function
object as the first argument.The function object could be a pre-defined method with a name (like
def add(x,y)
), though, more often than not, would be the ones you’d use only once. -
map(function_to_apply, list_of_inputs)
map()
applies a function to all the items in an input_list. -
filter(function, list_of_inputs)
filter()
forms a new list that contains only elements that satisfy a certain condition. -
reduce(function, sequence[, initial])
reduce()
works differently thanmap()
andfilter()
.Instead return a new list based on the
function
anditerables
we’ve passed, it returns a single value.In Python 3,
reduce()
isn’t a built-in function anymore, it can be found in thefunctools
module.reduce()
works by calling thefunction
we passed for the first two items in the sequence. The result returned by thefunction
is used in another call tofunction
alongside with the next (third in this case) element.The optional argument
initial
is used, when present, at the beginning of this “loop” with the first element in the first call tofunction
. -
References
理解reduce(), map(), filter(), anonymous in Python
最新推荐文章于 2024-08-23 16:53:34 发布