Sort list of tuples by specific ordering - Python
Last Updated :
17 Jan, 2025
Sorting a list of tuples by a specific order requires us to define a custom logic for the sorting process.
For example, given a list of tuples like [(1, 'Python'), (2, 'with'), (3, 'GFG')]
, we might want to sort it based on a predefined order of the second element such as ['with', 'GFG', 'Python']
. Let's explore different methods to achieve this in Python.
Using sorted() with a custom key
This method uses the sorted() function, which allows us to pass a custom key function for sorting.
Python
# Input list of tuples
a = [(1, 'Python'), (2, 'with'), (3, 'GFG')]
# Define the specific order
order = ['with', 'Python', 'GFG']
# Sort the list of tuples based on the specific order
res = sorted(a, key=lambda x: order.index(x[1]))
print(res)
Output[(2, 'with'), (1, 'Python'), (3, 'GFG')]
Explanation:
- We define the order of the elements in the list
order
. - key function uses the
index()
method to find the position of the second element of each tuple in the predefined order list. - sorted() function arranges the tuples based on these positions.
Let's explore some more ways and see how we can sort list of tuples by specific ordering.
Using a dictionary for mapping
This method introduces a dictionary to map each element in the predefined order to its position. It improves efficiency compared to using index() repeatedly.
Python
# Input list of tuples
a = [(1, 'Python'), (2, 'with'), (3, 'GFG')]
# Define the specific order
order = ['with', 'GFG', 'Python']
# Create a mapping of elements to their positions
order_map = {value: index for index, value in enumerate(order)}
# Sort the list of tuples using the mapping
res = sorted(a, key=lambda x: order_map[x[1]])
print(res)
Output[(2, 'with'), (3, 'GFG'), (1, 'Python')]
Explanation:
- We create a dictionary
order_map
to store the position of each element in the predefined order list. - The key function directly retrieves the position of the second element from the dictionary instead of repeatedly calling index().
Using for loop
This method involves manually sorting the list of tuples using a loop and comparing each element with the predefined order list.
Python
# Input list of tuples
a = [(1, 'Python'), (2, 'with'), (3, 'GFG')]
# Define the specific order
order = ['with', 'GFG', 'Python']
# Initialize an empty list to store the sorted tuples
res = []
# Iterate through the predefined order
for item in order:
for i in a:
if i[1] == item:
res.append(i)
print(res)
Output[(2, 'with'), (3, 'GFG'), (1, 'Python')]
Explanation:
- We manually iterate through the predefined order and check for matching elements in the original list of tuples.
- Matching tuples are added to the result list in the correct order.
- While simple, this method is the least efficient due to the nested loops, making it unsuitable for large datasets.
Similar Reads
Python - Order Tuples by List Sometimes, while working with Python tuples, we can have a problem in which we need to perform ordering of all the tuples keys using external list. This problem can have application in data domains such as Data Science. Let's discuss certain ways in which this task can be performed. Input : test_lis
7 min read
Sort Tuple of Lists in Python The task of sorting a tuple of lists involves iterating through each list inside the tuple and sorting its elements. Since tuples are immutable, we cannot modify them directly, so we must create a new tuple containing the sorted lists. For example, given a tuple of lists a = ([2, 1, 5], [1, 5, 7], [
3 min read
Python - Sort Tuple List by Nth Element of Tuple We are given list of tuple we need to sort tuple by Nth element of each tuple. For example d = [(1, 5), (3, 2), (2, 8), (4, 1)] and k=1 we need to sort by 1st element of each tuple so that output for given list should be [(4, 1), (3, 2), (1, 5), (2, 8)]Using sorted() with lambdasorted() function wit
3 min read
Python program to sort a list of tuples alphabetically Given a list of tuples, write a Python program to sort the tuples alphabetically by the first item of each tuple. Examples: Input: [("Amana", 28), ("Zenat", 30), ("Abhishek", 29), ("Nikhil", 21), ("B", "C")] Output: [('Amana', 28), ('Abhishek', 29), ('B', 'C'), ('Nikhil', 21), ('Zenat', 30)] Input:
3 min read
Custom Sorting in List of Tuples - Python The task of custom sorting in a list of tuples often involves sorting based on multiple criteria. A common example is sorting by the first element in descending order and the second element in ascending order. For example, given a = [(7, 8), (5, 6), (7, 5), (10, 4), (10, 1)], sorting the tuples by t
3 min read