# Sorting Two Lists Together According to The Order of One List in Python

Posted on

We may use two lists to store the values of two properties of a list of elements in Python. Under such data structure arrangement, when we need to sort the properties from one list, we may want to also make sure the other list will be also re-ordered following the same order as the first list.

For example, we may have two lists containing the x and y coordinates of points.

``````x = [3, 5, 6, 1, 2]
y = [6, 7, 8, 9, 10]``````

If we sort the points by their x coordinates, we want to sort the lists `x` and `y` together according to the orders of values in the list `x`.

## TL;DR zip-sort-unzip

To sort 2 lists `x` and `y` by `x`:

``new_x, new_y = zip(*sorted(zip(x, y)))``

## Functions used to sort two lists together

We can achieve this by using 3 built-in functions: `zip(list1, list2)`, `sorted(list)` and `zip(*list)`.

`zip(list1, list2)` returns a zip object by pairing the elements at the same positions from both lists. For the above example, `zip(x, y)` will be

``````>>> for elem in zip(x, y):
...     print(elem)
...
(3, 6)
(5, 7)
(6, 8)
(1, 9)
(2, 10)``````

`sorted(list)` returns the sorted list. For the above zip object containing the list of paired values, the sorted() list will be as follows.

``````>>> for elem in sorted(zip(x, y)):
...     print(elem)
...
(1, 9)
(2, 10)
(3, 6)
(5, 7)
(6, 8)``````

The values are now sorted, but paired. We can then use `zip(*list)` to decouple the list of paired elements to 2 lists.

``````>>> for elem in zip(*sorted(zip(x, y))):
...     print(elem)
...
(1, 2, 3, 5, 6)
(9, 10, 6, 7, 8)``````

## Python code to sort two lists according to one list

Combining them together, we can order the 2 lists together by

``new_x, new_y = zip(*sorted(zip(x, y)))``

For the above example, the `new_x` and `new_y` will be:

``````>>> new_x, new_y = zip(*sorted(zip(x, y)))
>>> new_x
(1, 2, 3, 5, 6)
>>> new_y
(9, 10, 6, 7, 8)``````

Now we sorted both lists together. 