Conditional Expression Evaluation Using List Comprehensions

suggest change

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

For instance,

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

Example:

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

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

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.

Example:

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Conditionals:
* Conditional Expression Evaluation Using List Comprehensions

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
47 Conditionals
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve