[Tutor] Else in list comprehension
jfouhy@paradise.net.nz
jfouhy at paradise.net.nz
Sun May 8 05:54:48 CEST 2005
Quoting Max Noel <maxnoel_fr at yahoo.fr>:
> Apparently, no. I just tried:
>
> >>> b = [i for i in range(10) if (i % 2) == 0 else 0]
You can sometimes do a bit of trickery with and/or. eg:
>>> odds = [(i % 2 == 1 and i or -1) for i in range(10)]
>>> odds
[-1, 1, -1, 3, -1, 5, -1, 7, -1, 9]
The big gotcha here is if any of the data you are interested in could be 0. You
can progress to further trickery, but the payoff isn't always worth it.
Sometimes you just have to write a loop :-)
--
John.
More information about the Tutor
mailing list