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?
lambda
is useful when you want to use an anonymous function as a parameter to another function. If it's only being used in that one place, there's no need to assign a name to it.
The ability to assign a lambda to a variable just falls out of the orthogonality of the language: a variable can hold any type of value, and a function created by lambda is just a value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With