Custom Sorting in List of Tuples - Python
Last Updated :
13 Feb, 2025
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 the first element in descending order and then by the second element in ascending order would result in [(10, 1), (10, 4), (7, 5), (7, 8), (5, 6)].
Using sorted()
sorted() is commonly used for custom sorting when a new sorted list is needed without modifying the original. It allows the use of a key argument with a lambda function to define custom sorting logic . It is ideal when sorting tuples based on descending order of the first element and ascending order of the second element.
Python
a = [(7, 8), (5, 6), (7, 5), (10, 4), (10, 1)]
res = sorted(a, key=lambda x: (-x[0], x[1]))
print(res)
Output[(10, 1), (10, 4), (7, 5), (7, 8), (5, 6)]
Explanation: sorted(a, key=lambda x: (-x[0], x[1])) sorts the list of tuples a by the first element in descending order and if two tuples have the same first element, by the second element in ascending order.
Using sort()
sort() is similar to sorted() but sorts the list in-place, modifying the original list. It is efficient when us do not need to preserve the original list. For custom sorting can be applied using a lambda expression as the key parameter, useful for sorting tuples with different sorting orders for elements.
Python
a = [(7, 8), (5, 6), (7, 5), (10, 4), (10, 1)]
a.sort(key=lambda x: (-x[0], x[1]))
print(a)
Output[(10, 1), (10, 4), (7, 5), (7, 8), (5, 6)]
Explanation: a.sort(key=lambda x: (-x[0], x[1])) sorts the list of tuples a in place by the first element in descending order and if two tuples have the same first element, by the second element in ascending order. Unlike sorted(), sort() modifies the original list.
Using itemgetter()
itemgetter() from the operator module is a faster alternative to lambda when sorting by tuple elements. It is often used for sorting large datasets. For custom sorting e.g., descending by the first element and ascending by the second, it can be combined with multiple sort calls.
Python
from operator import itemgetter
a = [(7, 8), (5, 6), (7, 5), (10, 4), (10, 1)]
a.sort(key=itemgetter(1))
a.sort(key=itemgetter(0), reverse=True)
print(a)
Output[(10, 1), (10, 4), (7, 5), (7, 8), (5, 6)]
Explanation: a.sort(key=itemgetter(1)) orders tuples by the second element in ascending order and a.sort(key=itemgetter(0), reverse=True) orders tuples by the first element in descending order, while preserving the previous order for equal first elements .
cmp_to_key() from functools allows using a custom comparator function instead of a key. This is useful when sorting requires complex comparison logic. It is particularly helpful when sorting tuples based on multiple fields with different sort orders, such as descending by the first and ascending by the second.
Python
from functools import cmp_to_key
a = [(7, 8), (5, 6), (7, 5), (10, 4), (10, 1)]
res = sorted(a, key=cmp_to_key(lambda a, b: b[0] - a[0] if a[0] != b[0] else a[1] - b[1]))
print(res)
Output[(10, 1), (10, 4), (7, 5), (7, 8), (5, 6)]
Explanation: cmp_to_key() first sorts by the first element in descending order. If the first elements are equal, it sorts by the second element in ascending order.
Similar Reads
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 | Summation of tuples in list
Sometimes, while working with records, we can have a problem in which we need to find the cumulative sum of all the values that are present in tuples. This can have applications in cases in which we deal with a lot of record data. Let's discuss certain ways in which this problem can be solved. Metho
7 min read
Python | Convert String to list of tuples
Sometimes, while working with data, we can have a problem in which we have a string list of data and we need to convert the same to list of records. This kind of problem can come when we deal with a lot of string data. Let's discuss certain ways in which this task can be performed. Method #1: Using
8 min read
Python | List of tuples to String
Many times we can have a problem in which we need to perform interconversion between strings and in those cases, we can have a problem in which we need to convert a tuple list to raw, comma separated string. Let's discuss certain ways in which this task can be performed. Method #1: Using str() + str
8 min read
Convert List Of Tuples To Json String in Python
We have a list of tuples and our task is to convert the list of tuples into a JSON string in Python. In this article, we will see how we can convert a list of tuples to a JSON string in Python. Convert List Of Tuples To Json String in PythonBelow, are the methods of Convert List Of Tuples To Json St
3 min read
Python - Custom length tuples from String
Given a String, extract tuple list, with each tuple being of custom length, delimited using comma. Input : test_str = "6 6 7, 3 4, 2" Output : [(6, 6, 7), (3, 4), (2, )] Explanation : The customs lengths being 3, 2, 1 have been converted to tuple list. Input : test_str = "7, 7, 4" Output : [(7, ), (
4 min read
Python | Sort lists in tuple
Sometimes, while working with Python tuples, we can have a problem in which we need to sort the tuples which constitutes of lists and we need to sort each of them. Let's discuss certain ways in which this task can be performed. Method #1 : Using tuple() + sorted() + generator expression This task ca
5 min read
Python | Combining tuples in list of tuples
Sometimes, we might have to perform certain problems related to tuples in which we need to segregate the tuple elements to combine with each element of complex tuple element( such as list ). This can have application in situations we need to combine values to form a whole. Let's discuss certain ways
7 min read
How To Slice A List Of Tuples In Python?
In Python, slicing a list of tuples allows you to extract specific subsets of data efficiently. Tuples, being immutable, offer a stable structure. Use slicing notation to select ranges or steps within the list of tuples. This technique is particularly handy when dealing with datasets or organizing i
3 min read
Convert List of Tuples to List of Strings - Python
The task is to convert a list of tuples where each tuple contains individual characters, into a list of strings by concatenating the characters in each tuple. This involves taking each tuple, joining its elements into a single string, and creating a new list containing these strings.For example, giv
3 min read