[Tutor] Else in list comprehension

Max Noel maxnoel_fr at yahoo.fr
Sun May 8 04:08:37 CEST 2005


On May 8, 2005, at 03:02, Bernard Lebel wrote:

> Hello,
>
> I just started using list comprehensions (loving them!)
>
> I know you can add an if statement, but can you put in there an else?
> I could not find an example of this.
>

     Apparently, no. I just tried:

 >>> b = [i for i in range(10) if (i % 2) == 0 else 0]

     And it raises a SyntaxError.
     The "if" statement is a filter, not an operation. The "else"  
would be an abuse. You could, however, do the following instead:

 >>> def f(x):
...     if (x % 2) == 0: return i
...     else: return 0
...
 >>> b = [f(i) for i in range(10)]
 >>> b
[0, 0, 2, 0, 4, 0, 6, 0, 8, 0]


-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting  
and sweating as you run through my corridors... How can you challenge  
a perfect, immortal machine?"



More information about the Tutor mailing list