Python - Reverse Row sort in Lists of List
Last Updated :
22 Feb, 2025
We are given a list of lists where each inner list represents a row and our task is to sort each row in descending order while keeping the overall structure intact. For example, given a = [[5, 2, 8], [9, 1, 4], [6, 7, 3]], after sorting each row in reverse order, the result will be [[8, 5, 2], [9, 4, 1], [7, 6, 3]].
Using NumPy
NumPy is optimized for array operations, making sorting faster than Python’s built-in functions when handling large datasets. np.sort() sorts each row, and [:, ::-1] reverses the order.
Python
import numpy as np
a = np.array([[5, 2, 8], [9, 1, 4], [6, 7, 3]])
# Using NumPy’s sort()
res = np.sort(a)[:, ::-1]
print(res)
Output[[8 5 2]
[9 4 1]
[7 6 3]]
Explanation: np.sort(a) sorts all rows in ascending order and [:, ::-1] reverses each row to descending order.
Using heapq
heapq module in Python provides an implementation of the heap queue (priority queue) algorithm, which allows efficient extraction of the smallest or largest elements from a collection, heapq.nlargest(k, iterable) returns the k largest elements from the given iterable in descending order.
Python
import heapq
a = [[5, 2, 8], [9, 1, 4], [6, 7, 3]]
# Using heapq.nlargest()
res = [heapq.nlargest(len(row), row) for row in a]
print(res)
Output[[8, 5, 2], [9, 4, 1], [7, 6, 3]]
Explanation: heapq.nlargest(len(row),row) reverses every row in "a" and the final result in saved in the list res.
Using map() + sorted()
Another approach to solving this problem is using the map() function, which can be used to apply sorted(reverse=True) to each sublist, updating the existing list with rows sorted in descending order.
Python
a = [[4, 1, 6], [7, 8], [4, 10, 8]]
res = list(map(lambda x: sorted(x, reverse=True), a))
print(str(res))
Output[[6, 4, 1], [8, 7], [10, 8, 4]]
Explanation: map() applies sorted(x, reverse=True) to each sublist in 'a', sorting them in descending order and then list() method converts it to a list.
Using list comprehension + sorted()
This is yet another way in which we can pack the logic in one line using list comprehension and sorted() function with reverse = True to provide a compact alternative.
Python
a = [[4, 1, 6], [7, 8], [4, 10, 8]]
res = [sorted(row, reverse=True) for row in a]
print(str(res))
Output[[6, 4, 1], [8, 7], [10, 8, 4]]
Explanation: sorted(row, reverse=True) sorts each sublist in descending order, and list comprehension applies this to all rows, storing the result in res without modifying the original list.
Using loop + sort()
We can solve this problem by using a loop to iterate through each row. The sort() function along with reverse=True can be used to sort the rows in descending order.
Python
a = [[4, 1, 6], [7, 8], [4, 10, 8]]
for row in a:
row.sort(reverse=True)
print(str(a))
Output[[6, 4, 1], [8, 7], [10, 8, 4]]
Explanation: sort(reverse=True) method sorts each sublist in descending order based on its elements, modifying the original list in place.
Similar Reads
Python | Sort Flatten list of list The flattening of list of lists has been discussed earlier, but sometimes, in addition to flattening, it is also required to get the string in a sorted manner. Let's discuss certain ways in which this can be done. Method #1 : Using sorted() + list comprehension This idea is similar to flattening a l
7 min read
Python | Reverse Sort Row Matrix integration Often during problem solving we come across to many problems where we need to reverse sort the list. But sometimes we would also want to reverse sort another list so that the elements of are automatically shifted and remain at same index as the first list even after first list get reverse sorted. Le
7 min read
Reverse All Strings in String List in Python We are given a list of strings and our task is to reverse each string in the list while keeping the order of the list itself unchanged. For example, if we have a list like this: ['gfg', 'is', 'best'] then the output will be ['gfg', 'si', 'tseb'].Using For LoopWe can use a for loop to iterate over th
2 min read
Python - Sort Records by Kth Index List Sometimes, while working with Python Records, we can have a problem in which we need to perform Sorting of Records by some element in Tuple, this can again be sometimes, a list and sorting has to performed by Kth index of that list. This is uncommon problem, but can have usecase in domains such as w
4 min read
Python | Flatten and Reverse Sort Matrix The flattening of list of list has been discussed many times, but sometimes, in addition to flattening, it is also required to get the string in reverse sorted manner. Letâs discuss certain ways in which this can be done. Method #1: Using sorted() + reverse + list comprehension This idea is similar
6 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 - Reverse Range in String List Given a string list, reverse each element of string list from ith to jth index. Input : test_list = ["Geeksforgeeks", "Best", "Geeks"], i, j = 1, 2 Output : ['ee', 'es', 'ee'] Explanation : Range of strings are extracted. Input : test_list = ["Geeksforgeeks"], i, j = 1, 7 Output : ['eeksfor'] Explan
3 min read
Python | Reverse each tuple in a list of tuples Given a list of tuples, write a Python program to reverse each tuple in the given list of tuples. Examples: Input : [(1, 2), (3, 4, 5), (6, 7, 8, 9)] Output : [(2, 1), (5, 4, 3), (9, 8, 7, 6)] Input : [('a', 'b'), ('x', 'y'), ('m', 'n')] Output : [('b', 'a'), ('y', 'x'), ('n', 'm')] Method #1 : Nega
5 min read
Python - Sort list of lists by the size of sublists The problem is to sort a list of lists based on the size of each sublist. For example, given the list [[1, 2], [1], [1, 2, 3]], the sorted result should be [[1], [1, 2], [1, 2, 3]] when sorted in ascending order. We will explore multiple methods to do this in Python.Using sorted() with len() This me
3 min read
Sort a List of Tuples by Second Item - Python The task of sorting a list of tuples by the second item is common when working with structured data in Python. Tuples are used to store ordered collections and sometimes, we need to sort them based on a specific element, such as the second item. For example, given the list [(1, 3), (4, 1), (2, 2)],
2 min read