Extended List Comprehension

Tim Chase python.list at tim.thechases.com
Fri Jan 20 16:26:12 EST 2006

>>py> [x for x in '1234' if x%2 else 'even']
>>[1, 'even', 3, 'even']
>>I'm guessing this has been suggested before?
> You could (in 2.5) use:
>    [(x if x%2 else 'even') for x in '1234']

This failed on multiple levels in 2.3.5 (the "if" syntax is 
unrecognized, and trying the below with '1234' rather than 
[1,2,3,4] choked)  Haven't played with 2.5 yet, so this might be 
a good way to go if you've got it.

However, this worked in my 2.3.5:

    [((x%2 == 0 and 'even') or x) for x in [-2,-1,0,1,2,3,4]]

It uses the fairly defacto short-circuit-evaluation usage to coin 
a Python trinary operator like the C/C++ colon/question-mark pair 
of operators.

There is a caveat (that can be coded around, IIRC, but don't have 
it at the tip of my fingers) that inverting the logic can cause 
trouble when x==0 as in

    [((x%2 == 0 and x) or 'odd') for x in [-2,-1,0,1,2,3,4]]

which doesn't quite produce the desired results.

-tim at justonemoretim.com

More information about the Python-list mailing list