using tuples instead of ternaries

🏠

Terneries in Python work just fine, however nested ternaries can lead to code that looks convoluted.

Standard form conditional

 1 i, j, r = 2, 3, 0
 2 if i > 1:
 3  if j == 3:
 4      r = 4
 5  else:
 6      r = 5
 7 else:
 8  r = 6
 9 
10 print(r)

Ternary

1 i, j = 2, 3
2 r = (4 if j == 3 else 5) if i > 1 else 5
3 print(r)

As illustrated above, ternaries have some syntacting issues in python, imo:

Tuples

Our shortest version of the code above is:

1 i, j = 2, 3
2 r = (6, (5, 4)[j == 3])[i > 1]
3 print(r)

We are converting the bool result of the conditional to an int (0 or 1) which we then use for tuple indexing. Please note we're using tuples rather than lists, since their immutability makes them presumably more efficient.

There are several advantages: