7

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.

A. Rodas
  • 20,171
  • 8
  • 62
  • 72

2 Answers2

14
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.

marr75
  • 5,666
  • 1
  • 27
  • 41
  • Thank you so much. That makes total sense. – user2195823 Mar 21 '13 at 15:54
  • No problem! And welcome to SO! We hope you stick with programming and around StackOverflow! Remember to "accept" one of these answers that was helpful by clicking the checkmark. If you plan to continue using SO, it will contribute to your reputation as an "asker". – marr75 Mar 21 '13 at 16:00
2

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.

danodonovan
  • 19,636
  • 10
  • 70
  • 78
  • 2
    Well, "python is a functional language" is a bit of a stretch. It's more an imperative language with functional features. – Gene Mar 21 '13 at 15:49
  • Enough features in other paradigms to be called "multi-paradigm"; like almost all mainstream languages. – marr75 Mar 21 '13 at 15:55