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,reducebuilt-in functions
mapbuilt-in functionmap(function, seq): taking item by item inseqand runningfunctionwith the item and returning the result as the type ofseq1
2
3
4
5def f(x):
return x * x
X - [1,2,3,4,5]
Y = map(f, X)
print YUsing
mapand lambda function - most recommended1
2X = [1,2,3,4,5]
print map(lambda x: x * x, X)
filterbuilt-in function- taking item by item in
seqand runningfunctionwith the item and returning the result as the type ofseqif the result isTrue1
print filter(lambda x: x>2, [1,2,3,45])
- taking item by item in
reducebuilt-in functionreduce(function, seq[,initial])- about each items in
seq, applyingfunctionand mapping as A value - the 1st paremeter(
function) should take two values(ex: x,y)- the items of
seqget intoy - the result after calling the function gets into
x
- the items of
- optionally, the 3rd parameter
initialis used as default value ofxat 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)