+ 3
Why we use lamdas in python
?
4 Answers
+ 7
I don't know if lambdas have any advantages over defined functions, they don't even seem to be much faster.
But in Python you can use functions like any other values, you can assign them to variables and store them as items in lists.
Maybe the advantage is on the fact that you can call lambda functions where you defined them, which can increase code readability.
Let's give an example where we need 3 functions in a list:
def sq(x): return x * x
def cb(x): return x**3
def sqrt(x): return x**0.5
fs = [sq, cb, sqrt]
You would need those 3 definitions, which make the code clearly longer.
With lambdas you can fit them all in 1 line:
fs = [lambda x: x*x, lambda x: x**3, lambda x: x**0.5]
I don't know if this is much more readable, maybe you would rather use:
fs = [
lambda x: x*x,
lambda x: x**3,
lambda x: x**0.5
]
But is this much better? Atleast you would not need to focus on function names.
+ 3
You can see a similar question
https://www.sololearn.com/Discuss/1550638/?ref=app
+ 1
Thank you