Python | Indices of sorted list of list elements
Last Updated :
08 Apr, 2023
Sorting is a common construct and there have been many variations of it being discussed. But sometimes, we need to perform the sorting on the list of list and moreover just require to find the order in which element occurs before getting sorted. Let's find out how to get indices of sorted order in list of lists.
Method #1 : Using List comprehension + enumerate() + sort() The combination of above 3 functions can be used to perform this particular task. In this, we perform the sorting taking triplets consisting of element and row and column coordinates and return them in 2nd step.
Python3
# Python3 code to demonstrate
# Indices of sorted list of list elements
# using List comprehension + enumerate() + sort()
# initializing list
test_list = [[4, 5, 1],
[9, 3, 2],
[8, 6]]
# printing original list
print("The original list : " + str(test_list))
# using List comprehension + enumerate() + sort()
# Indices of sorted list of list elements
res = [(i, j) for i, x in enumerate(test_list)
for j, k in enumerate(x)]
res.sort(key = lambda ij: test_list[ij[0]][ij[1]])
# print result
print("The indices of sorted order are : " + str(res))
Output :
The original list : [[4, 5, 1], [9, 3, 2], [8, 6]] The indices of sorted order are : [(0, 2), (1, 2), (1, 1), (0, 0), (0, 1), (2, 1), (2, 0), (1, 0)]
Time complexity: O(n^2 log n), where n is the total number of elements in the list of lists.
Auxiliary space: O(n), where n is the total number of elements in the list of lists.
Method #2 : Using sorted() + lambda The task performed above can be performed as arguments to the sorted function and lambda function performs the task of list comprehension function as above.
Python3
# Python3 code to demonstrate
# Indices of sorted list of list elements
# using sorted() + lambda
# initializing list
test_list = [[4, 5, 1],
[9, 3, 2],
[8, 6]]
# printing original list
print("The original list : " + str(test_list))
# using sorted() + lambda
# Indices of sorted list of list elements
res = sorted([(i, j) for i, x in enumerate(test_list)
for j, k in enumerate(x)],
key = lambda ij: test_list[ij[0]][ij[1]])
# print result
print("The indices of sorted order are : " + str(res))
Output :
The original list : [[4, 5, 1], [9, 3, 2], [8, 6]] The indices of sorted order are : [(0, 2), (1, 2), (1, 1), (0, 0), (0, 1), (2, 1), (2, 0), (1, 0)]
Time complexity: O(n^2 * log n). where N is the number of sublists in the test_list and M is the maximum length of any sublist
Auxiliary space: O(n^2).where N is the number of sublists in the input list and M is the maximum length of any sublist.
Method #3: Using heapq.nsmallest().
The algorithm used in the given code is as follows:
- Initialize an empty list res.
- For each row in test_list, find the smallest len(x) elements using heapq.nsmallest().
- For each element found in step 2, append a tuple (i, x.index(k)) to res, where i is the row index and x.index(k) is the column index of the element k.
- Sort the list of tuples res by the values of test_list at the corresponding indices.
- Print the sorted list of tuples.
Python3
import heapq
# initializing list
test_list = [[4, 5, 1],
[9, 3, 2],
[8, 6]]
# printing original list
print("The original list : " + str(test_list))
res = [(i, x.index(k)) for i, x in enumerate(test_list) for k in heapq.nsmallest(len(x), x)]
res.sort(key=lambda ij: test_list[ij[0]][ij[1]])
print("The indices of sorted order are:", res)
OutputThe original list : [[4, 5, 1], [9, 3, 2], [8, 6]]
The indices of sorted order are: [(0, 2), (1, 2), (1, 1), (0, 0), (0, 1), (2, 1), (2, 0), (1, 0)]
The time complexity of the algorithm is O(N*M*log(M)), where N is the number of rows in test_list and M is the maximum number of columns in any row. This is because for each row, we use heapq.nsmallest() to find the smallest M elements, which takes O(M*log(M)) time. Since we do this N times, the overall time complexity is O(N*M*log(M)).
The auxiliary space of the algorithm is O(N*M), since we store the list of tuples res that contains one tuple for each element in test_list.
Method 4 : Using Flattening and Sorting
- Initialize a list of lists test_list with integer values.
- Print the original list using the print() function.
- Use list comprehension to create a flattened list of all elements in the test_list and assign it to the variable flat_list. Also, create a list of indices from 0 to the length of flat_list - 1 and assign it to the variable indices.
- Sort the indices list based on the corresponding element in the flat_list. This is done using the sort() method with a key parameter that takes a lambda function that returns the value at the corresponding index of flat_list.
- Calculate the row and column indices from the sorted indices list by dividing each index by the number of columns in the original test_list and getting the floor division quotient as rows. The remainder after division gives the column index which is stored in cols.
- Zip the rows and cols lists together to create a list of tuples that represent the indices of the sorted order and assign it to the variable res.
- Print the result using the print() function.
Python3
# initializing list
test_list = [[4, 5, 1],
[9, 3, 2],
[8, 6]]
# printing original list
print("The original list : " + str(test_list))
# get flattened list and corresponding indices
flat_list = [element for sublist in test_list for element in sublist]
indices = list(range(len(flat_list)))
# sort the indices based on the corresponding element in flat_list
indices.sort(key=lambda x: flat_list[x])
# get row and column indices from sorted indices
rows = [index // len(test_list[0]) for index in indices]
cols = [index % len(test_list[0]) for index in indices]
# zip row and column indices and convert to list of tuples
res = list(zip(rows, cols))
# print result
print("The indices of sorted order are : " + str(res))
OutputThe original list : [[4, 5, 1], [9, 3, 2], [8, 6]]
The indices of sorted order are : [(0, 2), (1, 2), (1, 1), (0, 0), (0, 1), (2, 1), (2, 0), (1, 0)]
The time complexity of this method is O(nlogn), where n is the total number of elements in the nested list, because of the sorting operation.
The auxiliary space is also O(n) because we create a separate list to store the flattened version of the nested list and another list to store the corresponding indices.
Similar Reads
Python | Indices of N largest elements in list Sometimes, while working with Python lists, we can have a problem in which we wish to find N largest elements. This task can occur in many domains such as web development and while working with Databases. We might sometimes, require to just find the indices of them. Let's discuss a certain way to fi
5 min read
Python | Finding relative order of elements in list Sometimes we have an unsorted list and we wish to find the actual position the elements could be when they would be sorted, i.e we wish to construct the list which could give the position to each element destined if the list was sorted. This has a good application in web development and competitive
3 min read
Sorting List of Lists with First Element of Each Sub-List in Python In Python, sorting a list of lists by the first element of each sub-list is a common task. Whether you're dealing with data points, coordinates, or any other structured information, arranging the lists based on the values of their first elements can be crucial. In this article, we will sort a list o
3 min read
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 - Indices of atmost K elements in list Many times we might have problem in which we need to find indices rather than the actual numbers and more often, the result is conditioned. First approach coming to mind can be a simple index function and get indices less than or equal than particular number, but this approach fails in case of dupli
7 min read
Python | Sorting list of lists with similar list elements Sorting has always been a key operation that is performed for many applications and also as a subproblem to many problems. Many variations and techniques have been discussed and their knowledge can be useful to have while programming. This article discusses the sorting of lists containing a list. Le
5 min read