You could use this:
list1, list2 = zip(*sorted(zip(list1, list2)))
or this:
order = sorted(range(len(list1)), key=lambda i: list1[i])
list1 = [list1[i] for i in order]
list2 = [list2[i] for i in order]
The first one makes a new list that has matching pairs from list1
and list2
, then sorts the pairs, which will mainly focus on the values that came from list1
, and use the list2
value as a tiebreaker. Then zip(*new_list)
is a standard Python trick for splitting the pairs back into separate lists. It combines all the pairs together to make a new list with two long rows, one with the first item from each pair and one with the second item. Then assigning that list to two variables splits it into two lists.
The second one creates indexes for the items in both lists, then sorts the indexes using the corresponding item from list1
as a key. Then it retrieved the items from each list using the new ordering.
Or this hybrid may be more readable:
sorted_pairs = sorted(zip(list1, list2))
list1 = [v1 for v1, v2 in sorted_pairs]
list2 = [v2 for v1, v2 in sorted_pairs]