I have two numeric values with the names a
and b
.
I want to assign the name low
to the smaller value and the name high
to the larger value.
What's the pythonic way to do this?
I considered
low, high = sorted([a, b])
but that seems overkill.
CodePudding user response:
Why would it be overkill? sorted
is explicit, efficient and concise.
Just use: low, high = sorted([a, b])
CodePudding user response:
You can use a ternary conditional expression and tuple unpacking.
low, high = (a, b) if a < b else (b, a)
CodePudding user response:
The sorted function has time complexity O(n log n)
in worst case.
For small lists, this means it is very efficient. low, high = sorted([a, b])
is not overkill.
Alternatively, use a conditional expression: low, high = (a, b) if a < b else (b, a)