Sort the values of first list using second list in Python (original) (raw)

Last Updated : 11 Dec, 2025

Given two lists of equal length, where the second list defines the order, the task is to reorder the first list according to the sorted order of the second list.

**Example:

**Input:
List A (to sort): ['x', 'y', 'z', 'w']
List B (order list): [40, 10, 30, 20]

**Output:
['y', 'w', 'z', 'x']

**Explanation: List B tells us the order in which to arrange the elements of list A. The smallest value in B is 10, which corresponds to 'y' in A, next is 20 -> 'w', then 30 -> 'z', and finally 40 -> 'x'. So after sorting A based on B, we get ['y', 'w', 'z', 'x'].

Using zip() and sorted()

This method ties elements of both lists together and sorts them using the values from the second list.

Python `

a = ['a', 'b', 'c', 'd'] b = [3, 1, 4, 2]

x = [val for _, val in sorted(zip(b, a))] print(x)

`

Output

['b', 'd', 'a', 'c']

**Explanation:

Using numpy.argsort()

numpy.argsort() gives the index positions that would sort a list. Using these indices, we can reorder another list accordingly.

Python `

import numpy as np

a = ['a', 'b', 'c', 'd'] b = [3, 1, 4, 2] res = [a[i] for i in np.argsort(b)] print(res)

`

Output

['b', 'd', 'a', 'c']

**Explanation:

Using Pandas

Pandas sorts one list by another easily by putting both into a DataFrame and sorting by the second list.

Python `

import pandas as pd

a = ['a', 'b', 'c', 'd'] b = [3, 1, 4, 2]

df = pd.DataFrame({'a': a, 'b': b}) res = df.sort_values('b')['a'].tolist() print(res)

`

Output

['b', 'd', 'a', 'c']

**Explanation:

Using sorted() with a lambda key

This method sorts the first list by directly using values from the second list as the sorting key.

Python `

a = ['m', 'n', 'o', 'p'] b = [4, 1, 3, 2]

res = sorted(a, key=lambda x: b[a.index(x)]) print(res)

`