Conditional operator in Python?

Amit Patel amitp at Xenon.Stanford.EDU
Wed Apr 4 01:49:38 EDT 2001


 Tim Peters <tim.one at home.com> wrote:
| [Erik Max Francis]
| > ...
| > The Python FAQ, for instance, suggests x ? a : b can be reliably
| > substituted with
| >
| >     (x and [a] or [b])[0]
| >
| > which definitely works ([a] and [b] are singleton lists and always
| > evaluate true), but it makes the meaning unclear enough to defeat the
| > purpose of wanting to use a conditional operator in the first place.
| 
| LOL!  I "invented" that "idiom" for Python in the early 90's, in a silly
| thread where Steven Majewski and I tortured each other with the worst
| constructs we could dream up.  If you ever see production code that actually
| *uses* it, I encourage you to kill the author.

You don't even need 'and' / 'or' anymore:

(lambda t:([a for i in (1,) if t]+[b for i in (1,) if not t])[0])(x)

<duck>

      - Amit 
-- 
--
Amit J Patel, Computer Science Department, Stanford University
http://www-cs-students.stanford.edu/~amitp/



More information about the Python-list mailing list