(test) ? a:b

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Oct 24 09:07:02 EDT 2014


Marko Rauhamaa wrote:

> Steven D'Aprano <steve+comp.lang.python at pearwood.info>:
> 
>> So why is it hard to read when the index is a flag?
>>
>> value = [f, g][cond]()
> 
> So, subjectively, which syntax would you prefer:

Depends on what else the code is doing. But my personal preference is a red
herring: you didn't say that you "liked" or "preferred" one version over
the other, you said that the problem with the [f, g][cond] idiom is
readability, implying that it is hard to read. I'm not asking for your
personal preference, I'm asking for justification for your suggestion that
it is hard to read.


>     if j < 10:
>         j += 1
>     else:
>         j = 3
> 
> or:
> 
>     j = j + 1 if j < 10 else 3
> 
> or:
> 
>     j = (lambda: 3, lambda: j + 1)[j < 10]()

Certainly not the third one. That's needlessly obfuscated for the sake of
premature optimization. This version is much better, and probably not only
simpler and easier to read but probably more efficient too:

    j = (3, j + 1)[j < 10]



-- 
Steven




More information about the Python-list mailing list