ssjadon - 1 year ago 139

Python Question

What is the most pythonic way to sort a list of lists with a tie-breaker?

I can sort by sub-list length (longest to shortest):

`>>> l = [['c'], ['a', 'b'], ['b', 'c'], ['a', 'b', 'c']]`

>>> list(reversed(sorted(l, key=len)))

[['a', 'b', 'c'], ['b', 'c'], ['a', 'b'], ['c']]

But I want to preserve order when the lengths are equal, so the output I want is:

`[['a', 'b', 'c'], ['a', 'b'], ['b', 'c'], ['c']]`

Answer Source

Timsort (Python's built-in sorting algorithm) is stable, meaning it *keeps the original order* of elements with equal keys. However, you reversed the original order by using the `reversed`

function.

If you want to reverse the resulting list *and* preserve the original order of elements comparing equal, use `reverse=True`

:

```
In [3]: sorted(l, key=len, reverse=True)
Out[3]: [['a', 'b', 'c'], ['a', 'b'], ['b', 'c'], ['c']]
```