Why use lambdas vs 1-line function declarations?
function, lambda, python, python-3.x
Solution
Lambda functions don't need a name. They don't clog your namespace just for a function which is used only once.
a = [[1], [1, 2], [1, 2, 3]]
print min(a, key = lambda x:len(x))
print locals()
As you can see, though we created a lambda function (in this case, we could have directly used `len`), it does not add up to the local namespace.
They are use and throw type functions. They could be GCed after the line in which they are used, unless they are assigned to some variables.
They don't allow any python statements and assignments, so they can be little trusted with side-effects.
l = [1, 2]
lambda: l = []
This will throw an error, `SyntaxError: can't assign to lambda`. (You can mutate mutable objects though).
Sometimes, they can be used to beat the effect of closures.
Problem
The other day I wrote a lambda akin to the following: ``` fetch = lambda x: myDictionaryVariable.get(x, "") ``` But now I just learned that to a point you can separate python statements with a `;` instead of a newline and then learned that you can do simple statements on 1 line even with the colon. So I realized I could also write this: ``` def fetch(x): return myDictionaryVariable.get(x, "") ``` Not that I'm using the `;` here, but if I needed to I could, and thusly provide even more functionality for my 1-line function. I could write: ``` def strangeFetch(x): y = "unicorn"; return menu.get(x, y) ``` So why do I need lambdas at all? Why are they even a part of python? In view of this, what do they add?