(test) ? a:b
drsalists at gmail.com
Wed Oct 22 18:09:31 CEST 2014
On Wed, Oct 22, 2014 at 2:05 AM, <buscacio at gmail.com> wrote:
> Em quarta-feira, 22 de outubro de 2014 06h29min55s UTC-2, ast escreveu:
>> Is there in Python something like:
>> j = (j >= 10) ? 3 : j+1;
>> as in C language ?
> without not:
> j = [j+1, 3][j>=10]
> with not:
> j = [3, j+1][not (j>=10)]
This is not very readable, and eagerly evaluates the two list values.
A proper ternary operator will not evaluate the unused
candidate-result. This matters a little for performance, but matters
more if one or both of the candidate results have side-effects.
It's better to use "j = 3 if j >= 10 else j + 1".
What you've suggested here was one of the ternary operator workarounds
before a true ternary operator was introduced in 2.5.
I don't use Python's ternary operator much though - I tend to find
if+else more clear, and it shows up well in a debugger. The ternary
operator tends to lead to long one-liners (especially if nested!),
which are usually best avoided.
I'd even go so far as to say that most uses of a ternary operator
probably should be a small function. It's slower, but it lends itself
to DRY and abstraction better.
More information about the Python-list