Saturday, June 25, 2005

Python snippet

Picked up a trick from comp.lang.python. Probably "documented" elsewhere, but I put it here for easy reference...

Python lack the ?: conditional short-cut from for instance C. It is, however, possible to do:
a and b or c
There is, though, a small problem with this. If 'a' evaluates to True, the result should be 'b'. But if 'b' also evaluates to False, python will go on with 'c', and return the result of 'c'. A quick fix is:
(a and [b] or [c])[0].

As [b] always is True, regardless of 'b', the result will be [b] if 'a' is True, and the last [0] will extract the first entry from the list [b], which is 'b'.

Take care!

No comments: