strange syntax rules on list comprehension conditions

Paul McGuire ptmcg at austin.rr.com
Fri Jan 18 17:35:46 EST 2008


On Jan 18, 1:04 pm, "Chris Mellon" <arka... at gmail.com> wrote:
> On Jan 18, 2008 12:53 PM, Nicholas <nicholasinpa... at gmail.com> wrote:
>
> > I was quite delighted today, after extensive searches yielded nothing, to
> > discover how to place an else condition in a list comprehension.
> > Trivial mask example:
> > >>> [True if i <5 else False for i in range(10)]       # A
> > [True, True, True, True, True, False, False, False, False, False]
>

I think this would be preferred over your ternary-ish expression:

>>> [ i<5 for i in range(10) ]
[True, True, True, True, True, False, False, False, False, False]

Do you also write code like:

    if i<5 == True:
        blah...

If so, please just write:

    if i<5:
        better blah...

-- Paul



More information about the Python-list mailing list