/  Technology   /  How to sort a list in custom order in python?

How to sort a list in custom order in python?

In the previous article we’ve seen how we can sort a list of dictionaries using a custom order specified in another list. In this, we are going to do a simpler version of this, i.e. we would sort a simple list of tuples using a custom order specified in another list.

Let’s take an example and understand this scenario. We have 2 lists, list_1 and list_2, where the first list list_1 has the following elements.

 

Example:

list_1= [ ('p', 1), ('q', 2), ('r',3), ('s', 4)]

 

Output:

And the other list list_2 specifies the order in which we would like to sort the first list list_1.

 

Example:

list_2= ['s', 'p', 'q', 'r']

 

Output:

We can possibly solve this problem using two methods.

  • Using List Comprehension
  • Using sort(), lambda, index()

 

Using List Comprehension:

Refer this article to learn about List Comprehension.

List Comprehension.

 

In this approach we just check every element in list_2 whether it matches with the current tuple in list_1 or not, and append the new list result accordingly, in a sorted manner.

 

Example:

list_1= [ ('p', 1), ('q', 2), ('r',3), ('s', 4)]
list_2= ['s', 'p', 'q', 'r']

print("List 1 is : " + str(list_1))
print("List 2 is : " + str(list_2))

result= [tuple for i in list_2 for tuple in list_1 if tuple[0] == i]

print ("The custom order list is : " + str(result))

 

Output:

 

Using sort(), lamba, index():

We use a combination of these three functions in this approach. The sort() function does the required in-place sorting(without creating a separate list to store the sorted order) along with a lambda function with a key to specify the function execution for each pair of tuples, the index() function helps to get the order from our custom list list_2.

 

Example:

list_1= [ ('p', 1), ('q', 2), ('r',3), ('s', 4)]
list_2= ['s', 'p', 'q', 'r']

print ("List 1 is : " + str(list_1))
print ("List 2 is : " + str(list_2))

list_1.sort(key  = Lamda i: List_2.index(i[0]))
print ("The custom order list is : " + str(list_1))

 

Output:

 

Leave a comment