Python set variables to shorter list and list length I have a simple task that I can't find an elegant solution to. Say I have two arrays and I want to find which one is shorter and create variables for both their lengths (specifying them as long and short). Here's an inelegant way to do it:

l1 = len(arr1)
l2 = len(arr2)

if l1 &lt; l2:
    short_arr = arr1
    long_arr = arr2
    lshort = l1
    llong = l2
else:
    short_arr = arr2
    long_arr = arr1
    lshort = l2
    llong = l1


What's a better way to do it?
There is nothing inelegant about your code.  You are computing the length of each array exactly once, have one test, and assign variables in each of the two paths of the branch.  It is clean, fast, and efficient.

You could make it shorter by combining the assignments into structured assignment statement:

l1, l2 = len(arr1), len(arr2)

if l1 &lt; l2:
    short_arr, long_arr = arr1, arr2
    lshort, llong = l1, l2
else:
    short_arr, long_arr = arr2, arr1
    lshort, llong = l2, l1


but it is debatable whether that is clearer.



I can’t claim this is more elegant, but it is significantly shorter:

short_arr, long_arr = (arr1, arr2) if len(arr1) &lt; len(arr2) else (arr2, arr1)
lshort, llong = len(short_arr), len(long_arr)


And the absolutely wrong way to do it would be:

((lshort, short_arr), (llong, long_arr)) = sorted([(len(arr1), arr1), (len(arr2), arr2)])