How to sort two lists which reference each other in the exact same way with Python?

Sometimes, we want to sort two lists which reference each other in the exact same way with Python.

In this article, we’ll look at how to sort two lists which reference each other in the exact same way with Python.

How to sort two lists which reference each other in the exact same way with Python?

To sort two lists which reference each other in the exact same way with Python, we can use the zip and sorted functions.

For instance, we write

list1, list2 = (list(t) for t in zip(*sorted(zip(list1, list2))))

to call zip with with 2 lists to create a list with tuples with items in the 2 lists at the same position.

Then we call sorted to sort the items in the tuples list.

Next, we call zip again with the sorted tuples as the argument to create a tuple with 2 tuples with the items extracted from the tuples at each position and put into a tuple.

Then we unpack the lists by assigning them back to list1 and list2.

Conclusion

To sort two lists which reference each other in the exact same way with Python, we can use the zip and sorted functions.