Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nesting the ternary operator in Python

In the Zen of Python, Tim Peters states that Flat is better than nested.. If I have understood that correctly, then in Python, this:

<statement-1> if <condition> else <statement-2>

is generally preferred over this:

if <condition>:
    <statement-1>
else:
    <statement-2>

However, in other languages, I have been told not to nest the ternary operator, and the instead use the traditional if...else. My question, then, is should I use this:

(<statement-1> if <condition-1> else <statement-2>) if <condition-2> else <statement-3>

or

if <condition-2>:
    if <condition-1>:
        <statement-1>
    else:
        <statement-2>
else:
    <statement-3>

? Particularly if the statements and conditions are long, and the first line would need splitting?

like image 701
LazySloth13 Avatar asked Oct 28 '13 22:10

LazySloth13


People also ask

Can you nest ternary operators?

Nested Ternary operator: Ternary operator can be nested. A nested ternary operator can have many forms like : a ? b : c.

How do you define a ternary operator in Python?

Practical Data Science using Python Similarly the ternary operator in python is used to return a value based on the result of a binary condition. It takes binary value(condition) as an input, so it looks similar to an “if-else” condition block. However, it also returns a value so behaving similar to a function.

How do you write a 3 condition ternary operator?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.

What is ternary operator with example?

It helps to think of the ternary operator as a shorthand way or writing an if-else statement. Here's a simple decision-making example using if and else: int a = 10, b = 20, c; if (a < b) { c = a; } else { c = b; } printf("%d", c); This example takes more than 10 lines, but that isn't necessary.


2 Answers

"Flat is better than nested" is about module organization and perhaps data structures, not your source code. The standard library, for example, mostly exists as top-level modules with very little nesting.

Don't nest the ternary operator, or even use it at all if you can avoid it. Complex is better than complicated. :)

like image 139
Eevee Avatar answered Oct 30 '22 14:10

Eevee


Your first example (the horrid one-liner) is nested too. Horizontally nested. Your second example is vertically nested. They're both nested.

So which is better? The second one! Why? Because "sparse is better than dense" breaks the tie.

It's easy when you're Tim Peters - LOL ;-)

like image 38
Tim Peters Avatar answered Oct 30 '22 13:10

Tim Peters