M.M
M.M

Reputation: 1373

Switching the value with order

Is there a pythonic shorter version for the flowing code:

def method(a,b)
    if a > b:
        pass       
    else:
        a, b = b, a

Upvotes: 0

Views: 26

Answers (3)

Barmar
Barmar

Reputation: 781300

You can do it in a single assignment:

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

Upvotes: 1

steliosbl
steliosbl

Reputation: 8921

This is shorter:

def method(a,b)
    if a <= b:
        a, b = b, a

I suppose you could compress it into one line, but I don't know if it counts as more readable:

(a,b) = (b,a) if a <= b else (a,b)

Upvotes: 2

Austin
Austin

Reputation: 121

One easy simplification is to flip the conditional case. The default return for a Python method is None, so the end result is the same as your snippet.

def method(a, b):
  if a <= b:
    a, b = b, a

We might be able to do more if you provided more context around your question; what are you trying to accomplish?

Upvotes: 0

Related Questions