/  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.

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

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.

https://www.i2tutorials.com/list-comprehensions/

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.

 

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.

 

Leave a comment