How to do "new_variable = (variable) ? True : False; " (php) on python?

Sam Pointon free.condiments at gmail.com
Fri Nov 18 14:45:21 EST 2005


Daniel Crespo wrote:
> Hello to all,
>
> How can I do
>
> new_variable = (variable) ? True : False;
>
> in Python in one line?
>
> I want to do something like this:
>
> dic = {'item1': (variable) ? True-part : False-part}
>
> Any suggestions?
>
> Daniel

There's a trick using the short-circuiting boolean logic operators to
emulate the ternary operator in Python. Basically, you do
TEST and TRUE_PART or FALSE_PART

However, this fails if TRUE_PART evaluates to a False value; you end up
with FALSE_PART's value instead.

This is a trick/hack, though, and shouldn't really be used much - use
an if statement instead, or wait til 2.5 when an if expression is
coming in.




More information about the Python-list mailing list