What's the pythonic way to order exactly two values?

Viewed 46

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.

3 Answers

Why would it be overkill? sorted is explicit, efficient and concise.

Just use: low, high = sorted([a, b])

Talking about pythonic and performance, you could write low, high = sorted((a, b)), because tuples are almost always more performant than lists, but that's really a micro optimization.

Other than the call to BUILD_TUPLE instead of BUILD_LIST, there's no difference.

Here's the proof:

import dis
import timeit

print("list:")
dis.dis("low, high = sorted([a, b])")
print( timeit.timeit("[a, b]", setup="a,b=1,'x'", number=10000000) )
print("-"*60)
print("tuple:")
dis.dis("low, high = sorted((a, b))")
print( timeit.timeit("(a, b)", setup="a,b=1,'x'", number=10000000) )

Output:

list:
  1           0 LOAD_NAME                0 (sorted)
              2 LOAD_NAME                1 (a)     
              4 LOAD_NAME                2 (b)     
              6 BUILD_LIST               2
              8 CALL_FUNCTION            1
             10 UNPACK_SEQUENCE          2
             12 STORE_NAME               3 (low)   
             14 STORE_NAME               4 (high)  
             16 LOAD_CONST               0 (None)  
             18 RETURN_VALUE
0.47138820000000003
------------------------------------------------------------
tuple:
  1           0 LOAD_NAME                0 (sorted)
              2 LOAD_NAME                1 (a)
              4 LOAD_NAME                2 (b)
              6 BUILD_TUPLE              2
              8 CALL_FUNCTION            1
             10 UNPACK_SEQUENCE          2
             12 STORE_NAME               3 (low)
             14 STORE_NAME               4 (high)
             16 LOAD_CONST               0 (None)
             18 RETURN_VALUE
0.3673789999999999

Related: Are tuples more efficient than lists in Python?

Related