What is the best way to replace a ternary operator in Python?

Possible duplicate:
Python ternary conditional statement

If I have code like:

x = foo ? 1 : 2 

How do I translate it to Python? Can I do it?

 if foo: x = 1 else: x = 2 

Will x still be in the area outside the if / then blocks? Or do I need to do something like this?

 x = None if foo: x = 1 else: x = 2 
+7
python
Mar 13 '09 at 18:23
source share
6 answers

Use the ternary operator (formally conditional expression ) in Python 2.5+.

 x = 1 if foo else 2 
+26
Mar 13 '09 at 18:24
source share

The ternary operator specified is available only in Python 2.5. From WeekeePeedeea :

Although this was postponed for several years due to differences in syntax, the triple operator for Python was approved as Python Enhancement Proposition 308 and was added to the 2.5 release in September 2006.

Is the Python terminal operator different from the general ?: operator in the order of its operands; general view of op1 if condition else op2 . This form invites us to consider op1 as a normal value and op2 as an exceptional case.

Up to 2.5, you could use the ugly syntax (lambda x:op2,lambda x:op1)[condition]() , which also takes care only of evaluating the expressions that are actually necessary in order to prevent side effects.

+5
Mar 13 '09 at 18:49
source share

I am still using 2.4 in one of my projects and have come across this several times. The most elegant solution I see for this:

 x = {True: 1, False: 2}[foo is not None] 

I like it because it is a clearer logic test than using a list with indices 0 and 1 to get the return value.

+2
Mar 16 '09 at 18:34
source share

Duplicate of this .

I use this (although I am waiting for someone to launch or comment if it is incorrect):

 x = foo and 1 or 2 
+1
Mar 13 '09 at 18:29
source share

You can use something like:

 val = float(raw_input("Age: ")) status = ("working","retired")[val>65] print "You should be",status 

although he is not very pythonic

(other parameters are closer to C / PERL, but this is due to more tuple magic)

0
Mar 13 '09 at 18:24
source share

A good python trick uses this:

 foo = ["ifFalse","ifTrue"][booleanCondition] 

It creates a 2-member list, and the boolean becomes either 0 (false) or 1 (true), which selects the correct member. Not very readable, but pythony :)

-one
Mar 13 '09 at 18:53
source share



All Articles