0
Q:

lambda in python

add = lambda a, b : a + b
add(3,6) ## 9
30
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
5
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
8
even = lambda a: True if a % 2 == 0 else False
even(6) ## True
even(9) ## False
16
>>> sum = lambda x, y : x + y
>>> sum(3,4)
7
1

lambda arguments : expression
7
#lambda can be also used for adding string 
>>> full_name = lambda first, last: f'Full name: {first.title()} {last.title()}'
>>> full_name('guido', 'van rossum')
'Full name: Guido Van Rossum'
3
# This is a normal function:
def Function(Parameter):
  return Parameter

# And this is a lambda function
Function=lambda Parameter : Parameter

"""

They are both completely identical and do the exact same job (which is
to take in a parameter and output it) 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 like what
I did whilst defining functions are used for complex things.

You do not
have to use lambda functions, it's all about preference.

"""
3
def sumn(n):
  return lambda a: a + n
sum5 = sumn(5)
sum5(3) ## 8
7

New to Communities?

Join the community