Skip to content Skip to sidebar Skip to footer

How Does Python Break Tie When Sorting An Iterable

I wonder how Python decides the order between two items that would be in a tie based on some specified key of a sort. For example, given: l = [[1, 2, 3], [1, 2], [1], [2, 3, 4], [1

Solution 1:

Also in wiki:

Starting with Python 2.2, sorts are guaranteed to be stable. That means that when multiple records have the same key, their original order is preserved.

Solution 2:

From the docs:

The built-in sorted() function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).

Post a Comment for "How Does Python Break Tie When Sorting An Iterable"