Inline Conditionals?

Paul Rubin http
Thu Aug 26 22:59:11 CEST 2004


aleaxit at yahoo.com (Alex Martelli) writes:
> aux = []
> for x in Somelist:
>     if x.property:
>         aux.append(foo(x))
>     else
>         aux.append(foo(x))
> 
> would be vastly more readable; "sparse is better than dense" and any LC
> is far too dense to be Pythonic here.

Hmm,

    [ x.property ? foo(x) : bar(x) for x in Somelist ]

doesn't seem too dense, unless you consider -every- LC to be too
dense, in which case why have them?  The LC seems to me to be both
more readable and harder to get wrong, unlike your sparse example,
which has 'foo' on both branches of the conditional where you meant
'foo' and 'bar'.

I could see adding some parentheses in the LC to improve readability:

    [ (x.property ? foo(x) : bar(x)) for x in Somelist ]

but it doesn't seem like a big deal.



More information about the Python-list mailing list