How can I make this statement shorter?
How can I make this statement shorter?
A simple solution is to combine B
, C
and D
into one "value" using max
, so you only perform one explicit test. For example, instead of:
if A > B and A > C and A > D:
just write:
if A > max(B, C, D):
An alternative but functionally similar approach would be to use all
with a generator expression:
if all(A > x for x in (B, C, D)):
In theory, the generator expression approach is "faster", in that it performs fewer total comparisons and can short-circuit. That said, generator expressions have some overhead in terms of per loop Python byte code execution, so odds are the two perform similarly in practice, unless the objects in question have very expensive implementations of __gt__
(the overload for >
).
Note that if you don't need a single unique maximum, a slightly different behavior, but with far fewer tests, could be performed:
maxval = max(A, B, C, D)
if maxval is A:...
elif maxval is B:...
elif maxval is C:...
elif maxval is D:...
This does differ behaviorally though; unlike the other code, a tie here is resolved semi-arbitrarily with only one element "winning", where the code you describe would treat a tie as "no winner". Replacing is
with ==
and elif
with if
would treat a tie as "all tied for max are winners". It all depends on your desired behavior.