Python 3 sorting: Custom comparer removed in favor of key - why? Python 3 sorting: Custom comparer removed in favor of key - why? python-3.x python-3.x

Python 3 sorting: Custom comparer removed in favor of key - why?


Performance.

The cmp function was called every time the sorting algorithm needed a comparison between two elements.

In contrast, the key object can be cached. That is, the sorting algorithm only needs to get the key once for each element and then compare the keys. It doesn't need to get a new key for every comparison.


Sorting by keys is well-defined, meaning the result doesn't depend on which (stable) sorting algorithm you use. There's no pathological key function. You might suggest random.random(), but that simply shuffles the list.

Whereas sorting with a compare function is well-defined only if the function is transitive and antisymmetric, which Python can neither test nor prove. What happens if you sort by nonsense compare function lambda(x, y): 1? You can't say, the result depends on the algorithm. Some algorithms might not even terminate.