Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean evaluation in a lambda

Tags:

python

lambda

Just tooling around for my own amusement, and I want to use a lambda, because I feel like it. Can I replace this function with a lambda?

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

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

like image 480
SilentW Avatar asked Jul 22 '09 21:07

SilentW


2 Answers

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

(number % 2 != 0)

by itself is an expression that evaluates to True or False. Or even plainer,

bool(number % 2)

which you can simplify like so:

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

But if that's readable or not is probably in the eye of the beholder.

like image 93
Alexander Ljungberg Avatar answered Oct 20 '22 20:10

Alexander Ljungberg


Yes you can:

isodd = lambda x: x % 2 != 0
like image 38
Tomek Kopczuk Avatar answered Oct 20 '22 19:10

Tomek Kopczuk