Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use lambdas vs 1-line function declarations? [duplicate]

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?

like image 438
temporary_user_name Avatar asked Dec 20 '13 03:12

temporary_user_name


1 Answers

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.

like image 180
Barmar Avatar answered Sep 29 '22 12:09

Barmar