Compare function for lists I need to sort a list of lists. The following is a compare function:

def compare(lhs, rhs): # lhs&amp;rhs are lists
    delta = len(lhs) - len(rhs)
    if delta &gt; 0:
        return 1
    elif delta &lt; 0:
        return -1
    if lhs &lt; rhs:
        return 1
    elif lhs &gt; rhs:
        return -1
    return 0


It looks pretty wordy. Is there a way to rewrite the function without performance penalty?
If I understand correctly, you want to sort lists by their length first, and then by "whatever lists are otherwise sorted by". I also assume that you want to pass your function as the cmp argument to the list.sort or sorted function.

You can do this in both a more natural to read, and computationally more efficient way, by using the key argument instead:


  In general, the key and reverse conversion processes are much faster
  than specifying an equivalent cmp function. This is because cmp is
  called multiple times for each list element while key and reverse
  touch each element only once.


(Source: https://docs.python.org/2/library/stdtypes.html#mutable-sequence-types)

This should be the appropriate key function for your case:

def length_first(lst):
    return len(lst), lst


Or simply:

lambda lst: len(lst), lst


Example:

&gt;&gt;&gt; from random import randrange
&gt;&gt;&gt; lists = [[randrange(5) for _ in range(randrange(3, 6))]
...          for _ in range(10)]
&gt;&gt;&gt; print '\n'.join(map(str, sorted(lists, key=lambda lst: (len(lst), lst))))
[0, 0, 4]
[2, 3, 0]
[2, 4, 0]
[3, 4, 2]
[4, 1, 4]
[1, 0, 1, 0]
[2, 0, 1, 1]
[3, 1, 0, 4]
[0, 0, 0, 3, 2]
[4, 0, 1, 2, 1]