(test) ? a:b
bc at freeuk.com
Thu Oct 23 12:50:51 CEST 2014
"Dennis Lee Bieber" <wlfraed at ix.netcom.com> wrote in message
news:mailman.15097.1414022143.18130.python-list at python.org...
> On Wed, 22 Oct 2014 19:08:40 +0100, "BartC" <bc at freeuk.com> declaimed the
>> x = cond ? f() : g(); # C version
>> x = [f(), g()] [cond]
(Should probably be x = [g(), f()] [cond])
>>the latter evaluates both f() and g() instead of just one. Apart from
>>inefficient, it can have unintended side-effects.
> Ah, but what would
> x = [f, g][cond]()
It will select f or g (which should refer to functions), and call one of
those depending on cond. That's not a problem.
The problem is it will still evaluate both f and g, even if they are simple
in this case, and construct a list which is then indexed by cond. (Although
in this case a bytecode compiler might be smart enough to avoid constructing
the list, it can't do that with my example because the code might depend on
both those options being evaluated.)
More information about the Python-list