?: in Python

Bengt Richter bokr at oz.net
Wed Dec 14 16:06:53 EST 2005


On Wed, 14 Dec 2005 21:16:23 +0100, Lawrence Oluyede <raims at dot.com> wrote:

>Il 2005-12-14, Andy Leszczynski <yahoo at nospam.leszczynscy> ha scritto:
>> How can do elegantly in Python:
>>
>> if condition:
>>     a=1
>> else:
>>     a=2
>>
>> like in C:
>>
>> a=condition?1:2
>>
>
>There are tons of threads on this newsgroup and in the python-dev mailing
>list about a ternary operator. There's also a PEP AFAIK.
>
>I like this:
>
>In [1]:switch = True
>
>In [2]:a = (1, 2)[switch]
>
>In [3]:print a
>2
>
You won't like it in a case like
     a = (2**20**20, 2)[switch]
or
     a = (m/n, sys.maxint)[n==0]
the point is that if/else only evaluates
the expression in one branch, as with C ternary.

You're right, there is a PEP and a ternary expression
coming to python though.

Regards,
Bengt Richter



More information about the Python-list mailing list