Python Language Conditionals Conditional Expression Evaluation Using List Comprehensions


Python allows you to hack list comprehensions to evaluate conditional expressions.

For instance,

[value_false, value_true][<conditional-test>]


>> n = 16
>> print [10, 20][n <= 15]

Here n<=15 returns False (which equates to 0 in Python). So what Python is evaluating is:

[10, 20][n <= 15]
==> [10, 20][False] 
==> [10, 20][0]     #False==0, True==1 (Check Boolean Equivalencies in Python)
==> 10
Python 2.x2.7

The inbuilt __cmp__ method returned 3 possible values: 0, 1, -1, where cmp(x,y) returned 0: if both objecs were the same 1: x > y -1: x < y

This could be used with list comprehensions to return the first(ie. index 0), second(ie. index 1) and last(ie. index -1) element of the list. Giving us a conditional of this type:

[value_equals, value_greater, value_less][<conditional-test>]

Finally, in all the examples above Python evaluates both branches before choosing one. To only evaluate the chosen branch:

[lambda: value_false, lambda: value_true][<test>]()

where adding the () at the end ensures that the lambda functions are only called/evaluated at the end. Thus, we only evaluate the chosen branch.


count = [lambda:0, lambda:N+1][count==N]()