else condition in list comprehension

Dan Bishop danb_83 at yahoo.com
Sun Jan 9 17:04:40 EST 2005


Luis M. Gonzalez wrote:
> Hi there,
>
> I'd like to know if there is a way to add and else condition into a
> list comprehension. I'm sure that I read somewhere an easy way to do
> it, but I forgot it and now I can't find it...
>
> for example:
> z=[i+2 for i in range(10) if i%2==0]
> what if I want i [sic] to be "i-2" if i%2 is not equal to 0?

z = [i + (2, -2)[i % 2] for i in range(10)]

In general, the expression "T if C is true, or F if C is false" can be
written as (F, T)[bool(C)].  (If you know that C will always be either
0 or 1, as is the case here, the "bool" is redundant.)

Unless, of course, either F or T has side effects.  For a side-effect
free expression, you can use (C and [T] or [F])[0] or one of the many
other ternary operator substitutes.  (Search for PEP 308.)




More information about the Python-list mailing list