Boolean valuation in lambda

Just chat with your own entertainment and I want to use lambda because I like it. Can I replace this function with lambda?

def isodd(number): if (number%2 == 0): return False else: return True 

Elementary, yes. But I'm interested to know ...

+6
python lambda
source share
8 answers

And if you really don't need a function, you can replace it even without a lambda. :)

 (number % 2 != 0) 

is itself an expression that evaluates to True or False. Or even more understandable,

 bool(number % 2) 

which you can simplify as follows:

 if number % 2: print "Odd!" else: print "Even!" 

But if it is readable or not, it is probably in the eye of the beholder.

+12
source share
 lambda num: num % 2 != 0 
+8
source share

Yes, you can:

 isodd = lambda x: x % 2 != 0 
+8
source share
 isodd = lambda number: number %2 != 0 
+5
source share

Others have already given you answers that relate to your particular case. In general, however, when you really need an if -statement, you can use a conditional expression. For example, if you have to return the string "False" and "True" , and not boolean values, you can do this:

 lambda num: "False" if num%2==0 else "True" 

The definition of this expression in the Python language is as follows:

The expression x if C else y first evaluates to C (not x ); if C true, x is evaluated and its value is returned; otherwise y is evaluated and its value is returned.

+5
source share

And also don't forget that you can emulate complex conditional sentences with simple short circuit logic, taking advantage of "and" and "or" to return some of your elements (the latter is evaluated) ... for example, in this case, if you want to return what something other than True or False

 lambda x: x%2 and "Odd" or "Even" 
+3
source share

isodd = lambda number: (False, True)[number & 1]

+1
source share

Every time you see what you write:

 if (some condition): return True else: return False 

you should replace it with one line:

 return (some condition) 

Then your function will look like this:

 def isodd(number): return number % 2 != 0 

You should be able to see how to get from there to the lambda solution that others have provided.

0
source share

All Articles