else condition in list comprehension

Serhiy Storchaka1659322541 storchaka at ksf.kiev.ua
Tue Jan 11 13:14:01 EST 2005


Nick Coghlan wrote:

> Dan Bishop 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 [sic] to be "i-2" if i%2 is not equal to 0?
>>
>>
>>
>> z = [i + (2, -2)[i % 2] for i in range(10)]
> 
> 
> For the specific case of +/- a number, (-1) ** x works, too:
> 
> z = [i + 2 * ((-1) ** i) for i in range(10)]
> 
> Not that I'm claiming it's particularly readable or anything. . . just 
> that it works :)

Yet another variant:
z = [i + ( (i % 2) and -2 or 2 ) for i in range(10)]

-- 
Serhiy Storchaka



More information about the Python-list mailing list