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:
>>> from random import randrange
>>> lists = [[randrange(5) for _ in range(randrange(3, 6))]
... for _ in range(10)]
>>> 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]