1-line idiom to replace if blocks

Erik Max Francis max at alcyone.com
Tue Jan 21 09:21:44 CET 2003


"Jonathan P." wrote:

> I hate code that takes up too many lines and
> have come up with the ff. idiom to replace
> many 4 line if statements:
> 
> result=[value-if-false,value-if-true][condition]
> 
> This idea could also be applied as a compact
> switch block replacement in certain cases.

This works if you don't need to worry about short-circuiting issues
(i.e., you don't even want the true/false cases _evaluated_ unless
you're the selected), and you're sure that the condition expression will
evaluate to either 0 or 1.

In 2.2.x and greater, you can use [x, y][bool(p)] to get this; prior to
2.2 you could use [x, y][operator.truth(p)].  Obviously, a tuple instead
of a list will work just as well:  (x, y)[bool(p)].

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ The only source of knowledge is experience.
\__/ Albert Einstein
    Sade Deluxe / http://www.sadedeluxe.com/
 The ultimate Sade encyclopedia.




More information about the Python-list mailing list