1multiply = lambda x,y: x * y
2multiply(21, 2) #42
3#_____________
4def myfunc(n):
5 return lambda a : a * n
6
7mydoubler = myfunc(2)
8print(mydoubler(11)) #22
1Table = lambda Table_of,Multiply_by: (Table_of*Multiply_by)
2print("3 * 9 = ",Table(3,9))
3
4def Concatinate(first_name, last_name):
5 return first_name + " " + last_name
6print("Concatinate using functions your name is:- {}".format(Concatinate("Harit","rai")))
1Lamda is just one line anonymous function
2Useful when writing function inside function
3it can take multiple arguments but computes only one expression
4
5Syntax:
6 x = lambda arguments : expression
1nums = [1, 2, 3, 4, 5]
2
3
4print(list(map(lambda n:n*n, nums)))
5#lambda n : n in this case is the passed value
1# This is a normal function:
2def Function(Parameter):
3 return Parameter
4
5# And this is a lambda function
6Function = lambda Parameter : Parameter
7
8"""
9
10They are both equivalent and do the exact same job (which is
11to take in a parameter and output it, in this scenario) the reason
12lambda functions exist is to make code shorter and readable since
13a lambda function only takes up one line.
14
15Lambda functions are mostly used for simple things
16Whereas defining functions are used for complex things.
17
18You do not have to use lambda functions, it's all about preference.
19
20An example of where it would be used is in basic arithmetics, im only
21going to show addition, I think you can work out the rest:
22
23"""
24
25Add = lambda a, b: a + b
26
27print(Add(3,4))
28# Output:
29# >>> 7
30
31# Its equivalent:
32
33def Add(a ,b):
34 return a + b
35
36print(Add(3,4))
37# Output:
38# >>> 7