Rename Variable in Python Based on Condition

Question:

Let a=5 and b=6, I want to switch values when a < b. I can attempt this by making temporary variable say using code below

if a < b:
   a_temp = b
   b_temp = a
a = a_temp
b = b_temp

Is there an elegant way to do this without creating temporary variables?

Asked By: Lopez

||

Answers:

a,b = max(a,b),min(a,b)

Assigns to a the maximum value and to b the minimum value, which seems to be what you are looking for

Answered By: Enrico Agrusti