else condition in list comprehension

Stephen Thorne stephen.thorne at gmail.com
Wed Jan 12 18:57:01 EST 2005


On 9 Jan 2005 12:20:40 -0800, Luis M. Gonzalez <luismgz at gmail.com> 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?

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

C'mon, who needs an 'if' statement when we have maths!

Stephen.



More information about the Python-list mailing list