1

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.

actual_panda
  • 1,178
  • 9
  • 27

3 Answers3

1

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

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

mozway
  • 194,879
  • 13
  • 39
  • 75
1

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?

Mike Scotty
  • 10,530
  • 5
  • 38
  • 50
0

You can use a ternary conditional expression and tuple unpacking.

low, high = (a, b) if a < b else (b, a)
actual_panda
  • 1,178
  • 9
  • 27
  • This *is* faster than `sorted`, but it's also more verbose and more error-prone. This isn't going to be your bottleneck, so just going with `sorted` is probably better. – user2357112 Jul 28 '22 at 10:58