else condition in list comprehension
Reinhold Birkenfeld
reinhold-birkenfeld-nospam at wolke7.net
Sun Jan 9 16:38:43 EST 2005
Matteo Dell'Amico wrote:
> 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 to be "i-2" if i%2 is not equal to 0?
>
> You could use
>
> [(i-2, i+2)[bool(i%2 == 0)] for i in range(10)]
>
> or, in a less general but shorter way
>
> [(i+2, i-2)[i%2] for i in range(10)]
>
> or even
>
> [i%2 and i-2 or i+2 for i in range(10)]
One should note that the (cond and X or Y) construct only works if X can
never produce a false value (such as 0, "", []). In this example, it is
okay, but replace 2 with 1 and you will run into trouble for i = 1.
Reinhold
More information about the Python-list
mailing list