Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble understanding lambda functions [duplicate]

Tags:

python

lambda

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.

like image 518
user2195823 Avatar asked Mar 21 '13 15:03

user2195823


2 Answers

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.

like image 89
marr75 Avatar answered Oct 21 '22 16:10

marr75


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.

like image 24
danodonovan Avatar answered Oct 21 '22 15:10

danodonovan