+ 1
Lambda or def?
Which one is better and why?
3 Answers
+ 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!
+ 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.