Open In App

Python | Sort list of list by specified index

Last Updated : 10 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

We can sort the list of lists by using the conventional sort function. This sort the list by the specified index of lists. Let’s discuss certain ways in which this task can be performed using Python.

Method 1: Using the bubble sort algorithm

Bubble sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.

Step-by-step approach:

  • Initialize a variable n to the length of the input list.
  • Loop through the list n times.
    • For each iteration, loop through the list from index 0 to index n-2.
      • For each pair of adjacent items, check if the second element of the left item is greater than the second element of the right item. If yes, swap the two items.
  • After completing all iterations, return the sorted list.

Below is the implementation of the above approach:

Python3




# initializing list
test_list = [['Rash', 4, 28], ['Varsha', 2, 20],
             ['Nikhil', 1, 20], ['Akshat', 3, 21]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# bubble sort list of lists based on second index
n = len(test_list)
for i in range(n):
    for j in range(n-1):
        if test_list[j][1] > test_list[j+1][1]:
            test_list[j], test_list[j+1] = test_list[j+1], test_list[j]
 
# printing result
print("List after sorting by 2nd element of lists : " + str(test_list))


Output

The original list is : [['Rash', 4, 28], ['Varsha', 2, 20], ['Nikhil', 1, 20], ['Akshat', 3, 21]]
List after sorting by 2nd element of lists : [['Nikhil', 1, 20], ['Varsha', 2, 20], ['Akshat', 3, 21], ['Rash', 4, 28]]

Time complexity: O(n^2)
Auxiliary space: O(1). 

Method 2: Sort list of lists using sort() + lambda

The anonymous nature of Python Lambda Functions indicates that they lack a name. The Python sort() can be used to perform this variation of sort by passing a function. The list can be sorted using the sort function both ascendingly and descendingly. 

Follow the below steps to implement the above idea:

  • Initialize a list named “test_list” with four nested lists, each containing a string and two integers.
  • Print the original list using the print() function and concatenation of a string and the “test_list” variable.
  • Sort the “test_list” using the sort() method with the key parameter set to a lambda function that returns the second element of each nested list, which is the integer at index 1.
  • Print the sorted list using the print() function and concatenation of a string and the “test_list” variable.

Below is the implementation of the above approach:

Python3




# initializing list
test_list = [['Rash', 4, 28], ['Varsha', 2, 20],
             ['Nikhil', 1, 20], ['Akshat', 3, 21]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# sort list of list
# sort by second index
test_list.sort(key=lambda test_list: test_list[1])
 
# printing result
print("List after sorting by 2nd element of lists : " + str(test_list))


Output

The original list is : [['Rash', 4, 28], ['Varsha', 2, 20], ['Nikhil', 1, 20], ['Akshat', 3, 21]]
List after sorting by 2nd element of lists : [['Nikhil', 1, 20], ['Varsha', 2, 20], ['Akshat', 3, 21], ['Rash', 4, 28]]

Time complexity: O(n log n) due to the sorting operation, where n is the length of the input list. 
Auxiliary space: O(1) because the sorting is done in-place and no additional data structures are used.

Method 3: Sort a list of lists using sorted() + itemgetter() 

The Itemgetter can be used instead of the lambda function to achieve similar functionality. itemgetter() is used to get the index element by which the sort operation needs to be performed.  

Step-by-step approach:

  • The program first imports the itemgetter function from the operator module.
  • It initializes a list of lists test_list with four elements, each containing three values.
  • It prints the original list using the print() function and string concatenation.
  • It then uses the sorted() function to sort the list of lists test_list by the second element of each sublist using the itemgetter() function as the key.
  • It assigns the sorted list to the variable res.
  • Finally, it prints the sorted list using the print() function and string concatenation.

Below is the implementation of the above approach:

Python3




from operator import itemgetter
 
# initializing list
test_list = [['Rash', 4, 28], ['Varsha', 2, 20],
             ['Nikhil', 1, 20], ['Akshat', 3, 21]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# sort list of list
# sort by second index
res = sorted(test_list, key=itemgetter(1))
 
# printing result
print("List after sorting by 2nd element of lists : " + str(res))


Output

The original list is : [['Rash', 4, 28], ['Varsha', 2, 20], ['Nikhil', 1, 20], ['Akshat', 3, 21]]
List after sorting by 2nd element of lists : [['Nikhil', 1, 20], ['Varsha', 2, 20], ['Akshat', 3, 21], ['Rash', 4, 28]]

Time complexity: O(n log n), where n is the number of elements in the input list.
Auxiliary space: O(n), where n is the number of elements in the input list.

 Method 4: use the heapq module’s heapify() and heappop() functions.

This method uses the heapify() function to convert the list into a heap and then repeatedly uses the heappop() function to extract the smallest element from the heap until it’s empty. This ensures that the resulting list is sorted based on the second element of each sublist.

  1. Import the heapq module which provides heap-based operations like heapify, heappop, etc.
  2. Initialize a list of lists called test_list with the values [[‘Rash’, 4, 28], [‘Varsha’, 2, 20], [‘Nikhil’, 1, 20], [‘Akshat’, 3, 21]].
  3. Print the original list test_list with a message saying “The original list is : “.
  4. Use the heapify function from heapq to convert test_list into a min-heap based on the second element of each sublist.
  5. Create an empty list called result_list.
  6. While test_list is not empty, do the following:
    a. Use the heappop function from heapq to remove and return the smallest element from test_list.
    b. Append the element returned in the previous step to result_list.
  7. Print the result list result_list with a message saying “List after sorting by 2nd element of lists : “.

Python3




import heapq
 
# initializing list
test_list = [['Rash', 4, 28], ['Varsha', 2, 20],
             ['Nikhil', 1, 20], ['Akshat', 3, 21]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# sort list of list
# sort by second index
heapq.heapify(test_list)
result_list = []
while test_list:
    result_list.append(heapq.heappop(test_list))
 
# printing result
print("List after sorting by 2nd element of lists : " + str(result_list))


Output

The original list is : [['Rash', 4, 28], ['Varsha', 2, 20], ['Nikhil', 1, 20], ['Akshat', 3, 21]]
List after sorting by 2nd element of lists : [['Akshat', 3, 21], ['Nikhil', 1, 20], ['Rash', 4, 28], ['Varsha', 2, 20]]

Time complexity O(n), where n is the length of the input list. This operation rearranges the elements in the list to satisfy the heap property”
Auxiliary space: O(1) 

 Method 5:  Using a custom function

The below implementation uses a function sort_list_of_lists that takes a list of lists lst and an index index. The function uses the sorted function to sort the list based on the specified index, using a lambda function as the key function. Then call this function on the test_list and the second index (1) to get the sorted list.

Python3




def sort_list_of_lists(lst, index):
    return sorted(lst, key=lambda x: x[index])
 
test_list = [['Rash', 4, 28], ['Varsha', 2, 20],
             ['Nikhil', 1, 20], ['Akshat', 3, 21]]
 
# sort by second index
result_list = sort_list_of_lists(test_list, 1)
 
# printing result
print("List after sorting by 2nd element of lists : " + str(result_list))


Output

List after sorting by 2nd element of lists : [['Nikhil', 1, 20], ['Varsha', 2, 20], ['Akshat', 3, 21], ['Rash', 4, 28]]

Time complexity: O(n log n), where n is the length of the list of lists lst. 
Auxiliary space: O(n), where n is the length of the list of lists lst.

Method 6 : using the numpy library. 

Here is the step-by-step approach using numpy:

  1. Import numpy library.
  2. Convert the list of lists to a numpy array using the numpy.array() method.
  3. Use the numpy.argsort() method to get the indices that would sort the array based on the specified index.
  4. Use the indices obtained from step 3 to sort the array using the numpy.take() method.
  5. Convert the sorted numpy array back to a list of lists using the numpy.ndarray.tolist() method.

Python3




import numpy as np
 
def sort_list_of_lists(lst, index):
    # convert list of lists to numpy array
    arr = np.array(lst)
     
    # get indices that would sort the array based on specified index
    indices = np.argsort(arr[:, index])
     
    # use indices to sort the array
    sorted_arr = np.take(arr, indices, axis=0)
     
    # convert sorted numpy array back to list of lists
    result_list = sorted_arr.tolist()
     
    return result_list
 
test_list = [['Rash', 4, 28], ['Varsha', 2, 20],
             ['Nikhil', 1, 20], ['Akshat', 3, 21]]
 
# sort by second index
result_list = sort_list_of_lists(test_list, 1)
 
# printing result
print("List after sorting by 2nd element of lists : " + str(result_list))


OUTPUT: 

List after sorting by 2nd element of lists : [['Nikhil', '1', '20'], ['Varsha', '2', '20'], ['Akshat', '3', '21'], ['Rash', '4', '28']]

Time complexity: The numpy.argsort() method has a time complexity of O(n log n), where n is the number of elements in the array. The numpy.take() method also has a time complexity of O(n log n). Therefore, the time complexity of this method is O(n log n).

Auxiliary space: The numpy.array() method and numpy.argsort() method both create new arrays, which require additional memory. Therefore, the auxiliary space complexity of this method is O(n).



Similar Reads

Python Program that prints elements common at specified index of list elements
Given a list of strings, the task is to write a Python program to extract all characters that are same at a specified index of each element of a list. Illustration: Input : test_list = ["geeks", "weak", "beak", "peek"] Output : ['e', 'k'] Explanation : e and k are at same at an index on all strings.Input : test_list = ["geeks", "weak", "beak", "pee
5 min read
Python program to return rows that have element at a specified index
Given two Matrices, the task is to write a Python program that can extract all the rows from both matrices which have similar elements at their Kth index, mapped at similar row positions. Examples: Input : test_list1 = [[1, 8, 3], [9, 2, 0], [6, 4, 4], [6, 4, 4]], test_list2 = [[1, 9, 3], [8, 2, 3], [5, 4, 6], [5, 4, 6]], K = 1 Output : [[9, 2, 0],
5 min read
Minimum index i such that all the elements from index i to given index are equal
Given an array arr[] of integers and an integer pos, the task is to find the minimum index i such that all the elements from index i to index pos are equal. Examples: Input: arr[] = {2, 1, 1, 1, 5, 2}, pos = 3 Output: 1 Elements in index range [1, 3] are all equal to 1. Input: arr[] = {2, 1, 1, 1, 5, 2}, pos = 5 Output: 5 Brute Force Approach: A br
12 min read
Sort Array such that smallest is at 0th index and next smallest it at last index and so on
Given an array, arr[] of N integers, the task is to rearrange the array elements such that the smallest element is at the 0th position, the second smallest element is at the (N-1)th position, the third smallest element at 1st position, 4th smallest element is at the (N-2)th position, and so on for all integers in arr[]. Examples: Input: arr[] = {10
12 min read
Find the element at the specified index of a Spirally Filled Matrix
Given two integers x and y representing the row and column number in a matrix respectively, the task is to find the integer at the cell (x, y) in the Spirally Filled Matrix. Explanation: The size of the matrix change according to the insertion of elements. As the row and columns are filled layer - by - layer, a square matrix will be formed as each
7 min read
Find the element at specified index in a Spiral Matrix
Given two integers i and j, the task is to print the i * j thmatrix elements that can be obtained by filling the matrix in the following spiral manner: [caption width="800"]Spiral Grid Representation fig 1[/caption] Examples: Input: i = 3, j = 4Output: 12Explanation:i = 3, j = 4 and grid[3][4] = 12 Input: i = 5, j = 5Output: 21Explanation:i = 5, j
6 min read
Queries to update array by adding or multiplying array elements and print the element present at specified index
Given an array arr[] consisting of N integers and an array Q[] of M pairs representing a query of type {X, Y}, the task is to perform queries of the following type: Query(0, X): Add integer X to every array elements.Query(1, Y): Multiply each array element by Y.Query(2, i): Print the value at index i. Examples: Input: arr[] = {5, 1, 2, 3, 9}, Q[][]
9 min read
Sort an array by swapping elements of different type specified by another array
Given two arrays a[] and b[] which contain the integer elements and their respective types (either type 0 or type 1) respectively, the task is to check if it is possible to sort the array in non-decreasing order by swapping elements of different types only. Examples: Input: a[] = {30, 20, 20, 10}, b[] = {1, 1, 1, 1} Output: No Explanation: Since al
9 min read
Python - Sort dictionaries list by Key's Value list index
Given list of dictionaries, sort dictionaries on basis of Key's index value. Input : [{"Gfg" : [6, 7, 8], "is" : 9, "best" : 10}, {"Gfg" : [2, 0, 3], "is" : 11, "best" : 19}, {"Gfg" : [4, 6, 9], "is" : 16, "best" : 1}], K = "Gfg", idx = 0 Output : [{'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}, {'Gfg': [6, 7, 8],
14 min read
Comparison among Bubble Sort, Selection Sort and Insertion Sort
Bubble Sort, Selection Sort, and Insertion Sort are simple sorting algorithms that are commonly used to sort small datasets or as building blocks for more complex sorting algorithms. Here's a comparison of the three algorithms: Bubble Sort:Time complexity: O(n^2) in the worst and average cases, O(n) in the best case (when the input array is already
15 min read
Practice Tags :