+ 2
Lambdas V/S Functions
When should you use lambda functions in python? And when should use the def keyword. What are the advantages of both?
2 ответов
+ 2
Lets look at the definition
when would you want to use lambda?
example:
---------
a=[1,2,3,4,5]
print(lambda x: x+1, a)
---------
this will return [2,3,4,5,6]
instead of having to do something like this:
---------
a=[1,2,3,4,5]
def add1(x):
return x+1
for i in range(len(a)):
a[i]=add1(a[i])
print(a)
---------
But when we have something like this:
a=int(input())
b=int(input())
#and we need to add 1 to each
---------
we dont want to use lambda, because it will be a mess, and if we want to use the function from that point onwards, its better to call it, instead of having to write a gazillion lambdas that do the same.
---------
TL;DR
In short, we use lambda functions once we require a nameless function for a brief period of your time. In Python, we generally use Lambda Functions as an argument to a higher-order function (a function that takes in other functions as arguments), but use functions as functions based on arguments, that will be used afterwards and can be called multiple times.
0
Got it! Thanks!