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
Python | Custom sorting in list of tuples
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
Slicing List of Tuples in Python
Slicing, a powerful feature in Python, allows us to extract specific portions of data from sequences like lists. When it comes to lists of tuples, slicing becomes a handy tool for extracting and manipulating data. In this article, we'll explore five simple and versatile methods to slice lists of tup
2 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
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 | 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
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, gi
3 min read
Lists Of Strings In Python
A list of strings in Python stores multiple strings together. In this article, weâll explore how to create, modify and work with lists of strings using simple examples. Creating a List of StringsWe can use square brackets [] and separate each string with a comma to create a list of strings. [GFGTABS
2 min read
Create a List of Strings in Python
Creating a list of strings in Python is easy and helps in managing collections of text. For example, if we have names of people in a group, we can store them in a list. We can create a list of strings by using Square Brackets [] . We just need to type the strings inside the brackets and separate the
3 min read