?: in Python

Peter Hansen peter at engcorp.com
Wed Dec 14 16:12:57 EST 2005


Andy Leszczynski wrote:
> Lawrence Oluyede wrote:
>>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
> 
> Like it too, thx. Switch does not have to be bool, so it is more 
> powerfull than ?:.

Actually, if "switch" is neither bool nor a number that equals 0 or 1, 
you'll have trouble...  using bool(switch) instead would do what you 
thought that did, I guess.

-Peter




More information about the Python-list mailing list