What exactly is happening 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'm a noob to any form of code.
some_function = lambda x: 10 if x == 6 else 1
is syntactic sugar for:
def some_function(x):
return 10 if x == 6 else 1
Meaning that it will return 10 if x == 6
evaluates to True and return 1 otherwise.
Personally, I prefer the def
form in all but the simplest cases as it allows multi-line functions, makes it more clear what kind of overhead is involved with invoking the callable, makes analyzing the closure of the function simpler, and opens the mind of the new python programmer to other, more complex code objects (such as classes) which can just as easily be constructed at run-time.
As python is a great language with functional features you can do handy things with functions using lambdas. Your example is equivalent to
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.
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