Problems understanding lambda functions

What exactly happens in the function:

lambda x: 10 if x == 6 else 1 

I know what some lambda functions do, but I'm not used to seeing them written like this. I am noob for any form of code.

+6
source share
2 answers
 some_function = lambda x: 10 if x == 6 else 1 

- syntactic sugar for:

 def some_function(x): return 10 if x == 6 else 1 

The value is that it will return 10 if x == 6 evaluates to True and returns 1 otherwise.

Personally, I prefer the def form in all but the simplest cases, since it allows multi-line functions, makes it clearer what overhead is associated with calling the callee, simplifies the analysis of closing the function, and opens the mind of the new python programmer to other, more complex code objects (such like classes) that can be just as easily created at runtime.

+14
source

Since python is a great language with functional functions, you can make convenient functions with functions using lambdas. Your example is equivalent

 if x == 6: return 10 else: return 1 

lambda functions are useful if you need to pass a simple function as an argument to another function somewhere in your code.

+2
source

All Articles