Is there something similar to ?: operator (C/C++) in Python?

Roy Smith roy at panix.com
Wed Jun 29 08:35:37 EDT 2005


Andrew Durdin <adurdin at gmail.com> wrote:
> Corrected version:
> 
>     result = [(lambda: expr0), lambda: expr1][bool(cond)]()

I'd go one step further.  Most people expect the first item to correspond 
to True and the second one to correspond to False.  So:

result = [(lambda: expr0), lambda: expr1][bool(not cond)]()

or perhaps even better:

result = [(lambda: expr0), lambda: expr1][1 - bool(cond)]()

or, if you prefer a slightly more deranged version:

result = [(lambda: expr0), lambda: expr1][bool(cond) - 1]()



More information about the Python-list mailing list