xxxxxxxxxx
#define a function inline
#(syntax) lambda parameter_list: expression parameter_list is comma separated
#lambda implicitly returns its expression's value, thus equivalent to any simple fxn of form...
'''
def function_name(parameter_list)
return expression
'''
numbers = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6]
print(list(filter(lambda x: x%2 != 0, numbers))) #here filter() takes a fxn as 1st argument
# [3, 7, 1, 9, 5]
xxxxxxxxxx
even = lambda a: True if a % 2 == 0 else False
even(6) ## True
even(9) ## False
xxxxxxxxxx
multiply = lambda x,y: x * y
multiply(21, 2) #42
#_____________
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11)) #22
xxxxxxxxxx
Lamda is just one line anonymous function
Useful when writing function inside function
it can take multiple arguments but computes only one expression
Syntax:
x = lambda arguments : expression
xxxxxxxxxx
# This is a normal function:
def Function(Parameter):
return Parameter
# And this is a lambda function
Function = lambda Parameter : Parameter
"""
They are both equivalent and do the exact same job (which is
to take in a parameter and output it in this scenario) the reason
lambda functions exist is to make code shorter and readable since
a lambda function only takes up one line.
Lambda functions are mostly used for simple things
Whereas defining functions are used for complex things.
You do not have to use lambda functions, it's all about preference.
An example of where it would be used is in basic arithmetics, im only
going to show addition, I think you can work out the rest:
"""
Add = lambda a, b: a + b
print(Add(3,4))
# Output:
# >>> 7
# Its equivalent:
def Add(a, b):
return a + b
print(Add(3,4))
# Output:
# >>> 7
xxxxxxxxxx
# lambda functions creates small anonymous function
# create an add functions with that takes two numbers and returns the sum
add = lambda num1, num2: num1 + num2
print(add(9, 5))
# output 14
# double the numbers in a list
print(list(map(lambda num1: num1 * 2, [1, 2, 3, 4])))
# output [2, 4, 6, 8]
xxxxxxxxxx
Lamda is just one line anonymous function
Useful when writing function inside function
it can take multiple arguments but computes only one expression
Syntax:
x = lambda arguments : expression
xxxxxxxxxx
Table = lambda Table_of,Multiply_by: (Table_of*Multiply_by)
print("3 * 9 = ",Table(3,9))
def Concatinate(first_name, last_name):
return first_name + " " + last_name
print("Concatinate using functions your name is:- {}".format(Concatinate("Harit","rai")))