+ 3

Why we use lamdas in python

?

23rd Feb 2020, 12:49 PM
Sai Deepika Kathiri
Sai Deepika Kathiri - avatar
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.
23rd Feb 2020, 1:05 PM
Seb TheS
Seb TheS - avatar
+ 3
23rd Feb 2020, 12:57 PM
Utkarsh Sharma
Utkarsh Sharma - avatar
+ 1
Thank you
23rd Feb 2020, 1:07 PM
Sai Deepika Kathiri
Sai Deepika Kathiri - avatar