Skip to content
Related Articles

Related Articles

Python | Sort list according to other list order

Improve Article
Save Article
  • Last Updated : 11 Jun, 2021
Improve Article
Save Article

Sorting is an essential utility used in majority of programming, be it for competitive programming or development. Conventional sorting has been dealt earlier many times. This particular article deals with sorting with respect to some other list elements. 
Let’s discuss certain ways to sort list according to other list order.
Method #1 : Using List comprehension 
List comprehension can be used to achieve this particular task. In this, we just check for each element in list 2 matches with the current tuple, and append accordingly, in a sorted manner.
 

Python3




# Python3 code to demonstrate
# to sort according to other list
# using list comprehension
 
# initializing list of tuples
test_list = [ ('a', 1), ('b', 2), ('c', 3), ('d', 4)]
 
# initializing sort order
sort_order = ['d', 'c', 'a', 'b']
 
# printing original list
print ("The original list is : " + str(test_list))
 
# printing sort order list
print ("The sort order list is : " + str(sort_order))
 
# using list comprehension
# to sort according to other list
res = [tuple for x in sort_order for tuple in test_list if tuple[0] == x]
 
# printing result
print ("The sorted list is : " + str(res))

Output: 

The original list is : [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
The sort order list is : ['d', 'c', 'a', 'b']
The sorted list is : [('d', 4), ('c', 3), ('a', 1), ('b', 2)]

 

  
Method #2 : Using sort() + lambda + index() 
The shorthand to perform this particular operation, sort function can be used along with lambda with key to specify the function execution for each pair of tuple, and list order of other list is maintained using index function. 
 

Python3




# Python code to demonstrate
# to sort according to other list
# using sort() + lambda + index()
 
# initializing list of tuples
test_list = [ ('a', 1), ('b', 2), ('c', 3), ('d', 4)]
 
# initializing sort order
sort_order = ['d', 'c', 'a', 'b']
 
# printing original list
print ("The original list is : " + str(test_list))
 
# printing sort order list
print ("The sort order list is : " + str(sort_order))
 
# using sort() + lambda + index()
# to sort according to other list
# test_list.sort(key = lambda(i, j): sort_order.index(i)) # works in python 2
test_list.sort(key = lambda i: sort_order.index(i[0])) # works in python 3
 
# printing result
print ("The sorted list is : " + str(test_list))

Output: 

The original list is : [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
The sort order list is : ['d', 'c', 'a', 'b']
The sorted list is : [('d', 4), ('c', 3), ('a', 1), ('b', 2)]

 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!