What would be a good reason to use Lambdas as a normal function? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

What would be a good reason to use Lambdas as a normal function?

example from lesson: double = lambda x: x * 2 print(double(7)) output 14

21st Dec 2017, 6:05 AM
Dipti Muni
Dipti Muni - avatar
2 Answers
+ 6
The syntax is more concise in certain situations, mostly when dealing with mapet al. ex:- map(lambda x: x * 2, [1,2,3,4]) seems better to me than: def double(x): return x * 2 map(double, [1,2,3,4]) I think the lambda is a better choice in this situation because the def double seems almost disconnected from the mapthat is using it. Plus, I guess it has the added benefit that the function gets thrown away when you are done. There is one downside to lambda which limits its usefulness in Python, in my opinion: lambdas can have only one expression (i.e., you can't have multiple lines). It just can't work in a language that forces whitespace.
21st Dec 2017, 6:27 AM
GAWEN STEASY
GAWEN STEASY - avatar
0
In C# I use lambdas a lot for simply calling functions with different but similar parameters than the delegate I need to pass. myVar.SetLogFunction(message => log.Write(LogStatus.Info, message));
21st Dec 2017, 7:23 AM
Jesse Bayliss
Jesse Bayliss - avatar