-1

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?

Lopez
  • 461
  • 5
  • 19
  • 2
    You can swap both in a single assignment with `if a < b: a, b = b, a`, or using `min`, `max` or unpack `sorted`: `b, a = sorted((a, b))` – tobias_k Sep 06 '22 at 07:50
  • 2
    [Also check this question](https://stackoverflow.com/questions/14836228/is-there-a-standardized-method-to-swap-two-variables-in-python) – RunOrVeith Sep 06 '22 at 07:53

1 Answers1

1
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

Enrico Agrusti
  • 507
  • 4
  • 15