Python | Sort the values of first list using second list


When it is required to sort the values of the first list with the help of the second list, the ‘sorted’ method and the ‘zip’ methods are used.

A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

The ‘sorted’ method is used to sort the elements of a list.

The zip method takes iterables, aggregates them into a tuple, and returns it as the result.

Below is a demonstration for the same −

Example

 Live Demo

def list_sort(my_list_1, my_list_2):
   zipped_list_pairs = zip(my_list_2, my_list_1)
   my_result = [x for _, x in sorted(zipped_list_pairs)]
   return my_result
my_list_1 = ['m', 'o', 'p', 'l', 'k', 'v', 'c', 'e', 'r']
my_list_2 = [ 1, 0,0, 2, 2, 1, 1, 0,0]
print("The first list is :")
print(my_list_1)
print("The second list is :")
print(my_list_2)
print("The first list is being sorted based on second list")
print(list_sort(my_list_1, my_list_2))
my_list_3 = ['h', 'k', 'l', 'p', 'q', 'p', 'k', 'l', 'h', 'm', 'u', 'z', 'f', 't']
my_list_4 = [ 0,1,1,1,0,2,2,2,0,2,1,2,1,0]
print("The third list is :")
print(my_list_3)
print("The fourth list is :")
print(my_list_4)
print("The third list is being sorted based on fourth list")
print(list_sort(my_list_3, my_list_4))

Output

The first list is :
['m', 'o', 'p', 'l', 'k', 'v', 'c', 'e', 'r']
The second list is :
[1, 0, 0, 2, 2, 1, 1, 0, 0]
The first list is being sorted based on second list
['e', 'o', 'p', 'r', 'c', 'm', 'v', 'k', 'l']
The third list is :
['h', 'k', 'l', 'p', 'q', 'p', 'k', 'l', 'h', 'm', 'u', 'z', 'f', 't']
The fourth list is :
[0, 1, 1, 1, 0, 2, 2, 2, 0, 2, 1, 2, 1, 0]
The third list is being sorted based on fourth list
['h', 'h', 'q', 't', 'f', 'k', 'l', 'p', 'u', 'k', 'l', 'm', 'p', 'z']

Explanation

  • A method named ‘list_sort’ is defined, that takes two lists as parameters.
  • It zips the two lists and stores it in another variable.
  • This is iterated over and sorted and assigned to another variable.
  • It is then displayed on the console as the result
  • Two lists are defined and displayed on the console.
  • The method is called on these lists.
  • It is then displayed as output on the console.

Updated on: 11-Mar-2021

364 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements