the definition of lambda function
- new literal defining usual functions by one line
- usually it is used for defining one-time functions
- after
:
, only expression can follow - lambda function is An object too
1 | f = lambda x: x + 1 |
Assigning variables and calling the lambda function having two parameters
1
2g = lambda x,y: x + y
print g(1,2)Defining the lambda function having default argument
1
2
3g = lambda x, inc=1: x+inc
print g(10) # default argument(inc=1) value is used
print g(10, 5)Defining the lambda function having variable argument
1
2
3#args is returned
vargs = lambda x, *args: args
print vars(1,2,3,4,5)
Using lambda functions
Using usual function
1
2
3
4
5
6
7
8
9
10
11def f1(x):
return x*x + 3*x - 10
def f2(x):
return x*x*x
def g(func):
return [func(x) for x in range(-10, 10)]
print g(f1)
print g(f2)Usiung lambda function
1
2
3
4
5def g(func):
return [func(x) for x in range(-10, 10)]
print g(lambda x: x*x + 3*x - 10)
print g(lambda x: x*x*x)
Utilizing lambda function
map
,filter
,reduce
built-in functions
map
built-in functionmap(function, seq)
: taking item by item inseq
and runningfunction
with the item and returning the result as the type ofseq
1
2
3
4
5def f(x):
return x * x
X - [1,2,3,4,5]
Y = map(f, X)
print YUsing
map
and lambda function - most recommended1
2X = [1,2,3,4,5]
print map(lambda x: x * x, X)
filter
built-in function- taking item by item in
seq
and runningfunction
with the item and returning the result as the type ofseq
if the result isTrue
1
print filter(lambda x: x>2, [1,2,3,45])
- taking item by item in
reduce
built-in functionreduce(function, seq[,initial])
- about each items in
seq
, applyingfunction
and mapping as A value - the 1st paremeter(
function
) should take two values(ex: x,y)- the items of
seq
get intoy
- the result after calling the function gets into
x
- the items of
- optionally, the 3rd parameter
initial
is used as default value ofx
at the 1st step1
2print reduce(lambda x, y: x + y, [1,2,3,4,5])
print reduce(lambda x, y: x + y, [1,2,3,4,5], 1000)