You can do it sorting by another element, a boolean
, indicating whether or not the second element is end
:
my_list.sort(key=lambda x: (x[0], x[1] != 'end'))
[[1, 'start'], [13, 'end'], [13, 'start'], [15, 'end']]
This will be using the following list of tuples in order to sort the list:
[(x[0], x[1] != 'end') for x in my_list]
[(1, True), (13, True), (13, False), (15, False)]
Where the second element will be False
if it is not end
in my_list
. Now sorting this array will yield the expected result, given that False
i.e. (0)
will come before True
(1)
when the first elements match:
sorted([(x[0], x[1] != 'end') for x in my_list])
[(1, True), (13, False), (13, True), (15, False)]
As @jpp points out you could simply sort by the second element lexicographically in this case:
my_list.sort()
[[1, 'start'], [13, 'end'], [13, 'start'], [15, 'end']]