To sort two lists together in Python, and preserve the order of pairs, you can use comprehension, zip() and sorted().

It is a little complicated, as we will explain here shortly, but here is some sample code for how you can sort two lists together using Python.

list1 = [1,4,4,2,3,3]
list2 = [8,7,6,9,9,3]

list1, list2 = (list(x) for x in zip(*sorted(zip(list1,list2), key=lambda pair:pair[0])))

print(list1)
print(list2)

#Output:
[1, 2, 3, 3, 4, 4]
[8, 9, 9, 3, 7, 6]

When working with collections of data, the ability to sort your data based on certain conditions easily can be very valuable.

One such operation is if you want to sort two lists together.

Sorting two lists together means sorting the first list and making sure that the pairwise elements stay in the same order.

To sort two lists together, you can use comprehension, zip() and sorted().

Let’s take this step by step. Below are two lists which we want to sort together.

list1 = [1,4,4,2,3,3]
list2 = [8,7,6,9,9,3]

First, we need to zip the two lists together.

list1 = [1,4,4,2,3,3]
list2 = [8,7,6,9,9,3]

print(list(zip(list1,list2)))

#Output:
[(1, 8), (4, 7), (4, 6), (2, 9), (3, 9), (3, 3)]

Then, we use sorted() with a lambda function passed to the key to sort by the element from the first list.

list1 = [1,4,4,2,3,3]
list2 = [8,7,6,9,9,3]

print(sorted(zip(list1,list2), key=lambda pair:pair[0]))

#Output:
[(1, 8), (2, 9), (3, 9), (3, 3), (4, 7), (4, 6)]

Next, we need to unpack the sorted result with *, and zip the result again to get back the original lists.

list1 = [1,4,4,2,3,3]
list2 = [8,7,6,9,9,3]

print(list(zip(*sorted(zip(list1,list2), key=lambda pair:pair[0]))))

#Output:
[(1, 2, 3, 3, 4, 4), (8, 9, 9, 3, 7, 6)]

Finally, we can use comprehension to get back the original lists and output it to the console.

Below is the full example of how you can sort two lists in Python.

list1 = [1,4,4,2,3,3]
list2 = [8,7,6,9,9,3]

list1, list2 = (list(x) for x in zip(*sorted(zip(list1,list2), key=lambda pair:pair[0])))

print(list1)
print(list2)

#Output:
[1, 2, 3, 3, 4, 4]
[8, 9, 9, 3, 7, 6]

Hopefully this article has been useful for you to learn how to sort two lists together using Python.

Categorized in:

Python,

Last Update: March 12, 2024