conditionals in lambdas?

Alex Martelli aleaxit at yahoo.com
Fri Nov 3 17:28:34 EST 2000


"Michael P. Soulier" <msoulier at nortelnetworks.com> wrote in message
news:8tv48r$kn8$1 at bmerhc5e.ca.nortel.com...
>     Hey people. If I want to put conditions in a lambda function, how
would
> I go about that?

Carefully; Python doesn't have built-in 'conditions' as expressions
(only as statements, which can't live inside a lambda).  But you
can fake it, much of the time, with indexing or other tricks.  E.g.:

def foobar(whop):
    if whop>"pohrw": return "foox"
    else: return "barbar"

==

foobar = lambda whop: ("foox", "barbar")[whop<="pohrw"]


> def test(string):
>     if string[:3] == 'yes:
>         return 1
>     else:
>         return 0
>
>     I'd like to make something like this a lambda function. Is that
possible?

Hey, is this a Brainbench test...?-)

test = lambda string: return string.startswith('yes')


Alex






More information about the Python-list mailing list