+ 1

Lambda or def?

Which one is better and why?

20th Aug 2021, 5:50 AM
Mohammad Hosein Soleymani
Mohammad Hosein Soleymani - avatar
3 ответов
+ 13
def is a keyword that doesn't return anything and creates a 'name' in the local namespace. lambda is a keyword that returns a function object and does not create a 'name' in the local namespace. Both are nice, in short: Use lambda if you want to make a short function once, use def for breaking problems in functions!
20th Aug 2021, 6:02 AM
Abhiyantā
Abhiyantā - avatar
+ 9
Rule of thumb: use a lambda if you only need that specific logic once in your program, and it fits in a single expression (one line). It is better to exctract code that you use multiple times, into a function (def) as per DRY principle (don't repeat yourself). And you cannot write multiple statements in a lambda.
20th Aug 2021, 9:46 AM
Tibor Santa
Tibor Santa - avatar
20th Aug 2021, 5:53 PM
Vitaly Sokol
Vitaly Sokol - avatar