Is there something similar to ?: operator (C/C++) in Python?

Steven D'Aprano steve at
Fri Jun 24 20:37:20 CEST 2005

On Fri, 24 Jun 2005 12:54:34 -0500, D H wrote:

> Riccardo Galli wrote:
>> On Fri, 24 Jun 2005 09:00:04 -0500, D H wrote:
>>>>Bo Peng wrote:
>>>>>I need to pass a bunch of parameters conditionally. In C/C++, I can
>>>>>do func(cond1?a:b,cond2?c:d,.....)
>>>>>Is there an easier way to do this in Python?
>>>The answer is simply no, just use an if statement instead.
>> That's not true.
>> One used form is this:
>> result = cond and value1 or value2
> So anywhere someone uses x?y:z you recommend they use "x and y or z" 
> instead, or else "[y,z][x]", but not:
> if x:
>     val = y
> else:
>     val = z

That's not what he said at all. Nowhere did Riccardo suggest that one or
the other method was better than if..else. The *most* he did was to
suggest a personal opinion that cond and value1 or value2 was "nice".

> I still would recommend just using an if statement, even though it is
> not easier to type than a ternary expression.

That's fine. Recommend it all you like. But it isn't the only way, and it
isn't even arguably the best or easiest or simplest way.

> It is the most readable
> and understandable equivalent in Python.

To you maybe. Actually, to me also. But "easier" doesn't just mean
"easier to read" -- it also means "easier to write", "easier to
maintain", "easier to insert in one-liners", "easier to put in lambda
functions", and maybe even "easier to delete when I no longer need it". 

For at least some of these requirements, the if..else solution is the
worst, not the best, solution.

> And since his question was
> about an easier way to do it in Python, and I don't believe your
> alternative are any easier either, I believe the answer is still no.

There's an easy way to settle this once and for all. If somebody can come
up with a good empirical test for "easier" (easier what?), we can run
some tests, get some hard figures for, eg, how many calories are expended
in typing one form over the other, and find out which is easier.

Until then, the question is at least partly a matter of personal taste,
and as such, there is no justification for such sweeping generalities as
"the answer is simply no, just use an if statement instead".


More information about the Python-list mailing list