Python: Conditional Statement with lambda

Tuesday, April 15th, 2008
Advertisement

Subscribe.
Enter your email:

Suppose that we have a conditional statement:

In Python, we can write it in three ways:

f = lambda x: x > 2 and (x + 1) or 0

or

f = lambda x: 0 if x <= 2 else (x + 1)

or

f = lambda x: [x + 1, 0][x <= 2]

However, if the number of conditions if more than 2, it is best to use the first method.

For example, consider this conditional statement:

Here is the Python code:

f = lambda x: (x >= 5 and x+1) or \
   ( (x < 5 and x > 2) and 3 ) or 0

We read it as:

if x >= 5, f(x) = x + 1
    else, if 2 < x < 5, f(x) = 3
    else, f(x) = 0
If you are new here, you might want to subscribe to the RSS feed or newsletter.

Enter your email address:

Creates the exact copy of your hard disk and allows you to instantly restore the entire machine.
New Acronis True Image Home 2010 is the most reliable and easy in use backup solution. Now with online backup option!
15% Discount Code: FMAATIH2010

What else?

Like this article? Share it

 Digg  del.icio.us  TwitThis  Facebook  Reddit  StumbleUpon

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>