(test) ? a:b

Ian Kelly ian.g.kelly at gmail.com
Fri Oct 24 14:22:33 EDT 2014


On Fri, Oct 24, 2014 at 7:07 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> >>     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]

Yes, the lambda approach falls victim to function calls being slow.

$ python3 -m timeit -s "j = 5" "if j < 10: j+=1
> else: j=3"
10000000 loops, best of 3: 0.0513 usec per loop
$ python3 -m timeit -s "j = 5" "j = j + 1 if j < 10 else 3"
10000000 loops, best of 3: 0.0519 usec per loop
$ python3 -m timeit -s "j = 5" "j = (3, j+1)[j < 10]"
10000000 loops, best of 3: 0.0883 usec per loop
$ python3 -m timeit -s "j = 5" "j = (lambda: 3, lambda: j+1)[j < 10]()"
1000000 loops, best of 3: 0.312 usec per loop



More information about the Python-list mailing list