Skip to content

Commit d7516fb

Browse files
committed
Update ternary_operators.rst
Added an important note regarding tupled ternary operators. They're avoided not just because they're not Pythonic, but also because the tuple itself is evaluated before a condition is chosen, leading to potential exceptions, problems, or slowdown.
1 parent 5321a78 commit d7516fb

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

ternary_operators.rst

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,30 @@ is some sample code:
4343
print("Ali is ", fitness)
4444
# Output: Ali is fat
4545
46+
This works simply because True == 1 and False == 0, and so can be done
47+
with lists in addition to tuples.
48+
4649
The above example is not widely used and is generally disliked by
4750
Pythonistas for not being Pythonic. It is also easy to confuse where to
4851
put the true value and where to put the false value in the tuple.
52+
53+
Another reason to avoid using a tupled ternery is that it results in
54+
both elements of the tuple being evaluated, whereas the if-else
55+
ternary operator does not.
56+
57+
**Example:**
58+
59+
.. code:: python
60+
61+
condition = True
62+
print(2 if condition else 1/0)
63+
#Output is 2
64+
65+
print((1/0, 2)[condition])
66+
#ZeroDivisionError is raised
67+
68+
This happens because with the tupled ternary technique, the tuple is
69+
first built, then an index is found. For the if-else ternary operator,
70+
it follows the normal if-else logic tree. Thus, if one case could
71+
raise an exception based on the condition, or if either case is a
72+
computation-heavy method, using tuples is best avoided.

0 commit comments

Comments
 (0)