File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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+
4649The above example is not widely used and is generally disliked by
4750Pythonistas for not being Pythonic. It is also easy to confuse where to
4851put 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.
You can’t perform that action at this time.
0 commit comments