else in list comp
Alex Martelli
aleax at aleax.it
Wed Jan 29 05:29:11 EST 2003
Cliff Wells wrote:
...
> myList = [0, None, '1', None, 2, None, '3']
>
> My real interest was in a possible "else" clause (as per the subject
> line) in a list comp.
>
> ['' for i in myList if i is None else i]
>
> It seems a good idea to me, but then, I'm somewhat biased toward my own
> ideas.
Seems too specialized to me. I'm strongly biased against adding
stuff to Python. I might solve this specific problem as follows:
[ [i, ''][i is None] for i in myList ]
IF (a BIG if) this is such a problem that it's worth adding stuff
to Python, then clearly the added stuff must be general -- namely,
a ternary (if not an even wider one-of-N) short-circuiting operator.
See the Python Cookbook for a LOT of discussion of ternary ops
(how to synthesize them in Python, and why no way is 100% OK yet,
although by one idiom or another one gets by without too many
problems about 99.44% of the time).
But limiting the application of such an addition to ONE specific
case, list comprehensions, would be horrible design IMHO.
Alex
More information about the Python-list
mailing list