FW: [Python-Dev] conditional expressions?
Huaiyu Zhu
huaiyu at gauss.almadan.ibm.com
Tue Oct 16 18:17:20 EDT 2001
On Tue, 16 Oct 2001 13:29:09 -0400, Steve Holden <sholden at holdenweb.com> wrote:
>I particularly shudder for the newbie who must read something like the
>following (untested code warning: I'm not building an interpreter that can
>handle this stuff, because I'm hoping it will disappear <0.75 wink>):
>
>l = if a then [i for i in l1 if i % 2] else [i for i in l2 if not i % 2]
>
>Of course, this might also be cast as:
>
>l = [i for i in (if a then l1 else l2) if (if a then i % 2 else not i % 2)]
>
>This may not be the best way to implement such an expression, but if it can
>be done then someone will do it. It contrasts quite badly with:
>
>if a:
> l = [i for i in l1 if i % 2]
>else:
> l = [i for i in l2 if not i % 2]
>
This proposed if-then-else expression is not in the same league of list
comprehension. The last example is a clear improvement to:
if a:
l = []
for i in l1:
if i % 2: l.append(i)
else:
l = []
for i l2:
if not i % 2: l.append(i)
In contrast, the example of if-then-else alone would be
l = []
for i in (if a then l1 else l2):
if (if a then i % 2 else not i % 2):
l.append(i)
which is not at all clear by itself, and not much an improvement to
l = []
if a: ll = l1
else: ll = l2
for i in ll:
if a: c = i % 2
else: c = not i % 2
if c: l.append(i)
In any case, bundling compoments of a list is usually a better strategy than
bundling branches of conditions.
Huaiyu
More information about the Python-list
mailing list