(test) ? a:b

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Oct 22 18:28:48 CEST 2014


Ned Batchelder wrote:

> On 10/22/14 5:05 AM, buscacio at gmail.com wrote:

>> without not:
>> j = [j+1, 3][j>=10]
>> with not:
>> j = [3, j+1][not (j>=10)]
>>
> 
> Why on earth would you recommend this outdated hack, when there's a true
> conditional operator?
> 
>      j = 3 if j >= 10 else j+1

I think that's a bit harsh. Especially since this appears to have been
Buscacio's first post here. Hopefully not his(?) last post!

The old (b, a)[condition] idiom is not outdated for anyone supporting Python
2.4, and I wouldn't call it a hack. Indexing into a sequence with a bool is
basic to Python's semantics: True and False are ints equal to 1 and 0
respectively. It's also a technique easily extensible to more than two
values:

    '01TX'[n % 4]

is in my opinion more readable than:

    i = n % 4
    '0' if i == 0 else '1' if i == 1 else 'T' if i == 3 else 'X'


> Of course, many people feel like the conditional operator isn't worth
> the squished-up unreadability, but if someone asks for a conditional
> operator, at least show them one!

The advantage of the `x if cond else y` operator is that it is a
short-cutting operator, it doesn't evaluate either x or y unless needed.
But for many cases that's not important, and in those cases I won't say I
prefer the old (y, x)[cond] idiom, but neither do I dislike it.


-- 
Steven




More information about the Python-list mailing list