Open In App

Sort the values of first list using second list in Python

Last Updated : 11 Dec, 2025
Comments
Improve
Suggest changes
19 Likes
Like
Report

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:

  • zip(b, a): pairs each value in b with corresponding value in a.
  • sorted(zip(b, a)): sorts pairs using values in b.
  • list comprehension: extracts sorted values of a.

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:

  • np.argsort(b): Returns the indices that would sort list b in ascending order.
  • [a[i] for i in np.argsort(b)]: Uses these indices to reorder elements of 'a' according to the sorted order of 'b'.

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:

  • pd.DataFrame({'a': a, 'b': b}): Creates a tabular structure with a and b.
  • sort_values('b'): Sorts rows based on column b.
  • ['a'].tolist(): Extracts the sorted a column as a Python list.

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)

Output
['n', 'p', 'o', 'm']

Explanation:

  • b[a.index(x)]: finds the matching value in list b for each x in a.
  • sorted(): arranges items in a based on the values in b.

Explore