Open In App

Python – Sort list according to other list order

Last Updated : 10 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Sorting a list based on the order defined by another list is a common requirement in Python, especially in scenarios involving custom sorting logic. This ensures that elements in the first list appear in the exact order specified in the second list. Python provides various methods to accomplish this.

Using sorted()

The sorted() function with key parameter allows sorting based on the index of elements in the reference list. This method is efficient and avoids manual looping.

Python
a = ['Python', 'with', 'GFG', 'Learn']
order = ['Learn', 'Python', 'with', 'GFG']

# Sort list 'a' based on 'order'
sorted_list = sorted(a, key=lambda x: order.index(x))
print(sorted_list)

Output
['Learn', 'Python', 'with', 'GFG']

Explanation:

  • sorted() iterates over each element in a and uses the index of the element in order to determine its position.

Let’s see some other methods to sort a list according to other list in Python

Using Dictionary Mapping

A dictionary can map elements in a to their corresponding positions in order. Sorting then uses these positions for arrangement. Sorting is performed using dictionary lookups which are faster than list indexing.

Python
a = ['with', 'GFG', 'Learn', 'Python']
order = ['Learn', 'Python', 'with', 'GFG']

# Create dictionary to map 'order' to their indices
order_dict = {value: index for index, value in enumerate(order)}

# Sort 'a' based on 'order' using the dictionary
sorted_list = sorted(a, key=lambda x: order_dict[x])
print(sorted_list)

Output
['Learn', 'Python', 'with', 'GFG']

Using Loops

Manual looping can also achieve sorting but is less efficient and more verbose. The loop iterates through order and appends matching elements from a.

Python
a = ['with', 'Python', 'Learn', 'GFG']
order = ['Learn', 'Python', 'with', 'GFG']

# Sort manually
sorted_list = []
for item in order:
    if item in a:
        sorted_list.append(item)
print(sorted_list)

Output
['Learn', 'Python', 'with', 'GFG']


Next Article

Similar Reads