Open In App
Related Articles

Python | Sort a list according to the second element in sublist

Improve Article
Improve
Save Article
Save
Like Article
Like

In this article, we will learn how to sort any list, according to the second element of the sublist present within the main list. We will see two methods of doing this. We will learn three methods of performing this sort. One by the use of Bubble Sort, the second by using the sort() method, and last but not the least by the use of the sorted() method. In this program, we have sorted the list in ascending order.

Illustration:

Input : [['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]
Output : [['akash', 5], ['rishav', 10], ['gaurav', 15], ['ram', 20]]
Input : [['452', 10], ['256', 5], ['100', 20], ['135', 15]]
Output : [['256', 5], ['452', 10], ['135', 15], ['100', 20]]

Method 1: Using the Bubble Sort Technique

Here we have used the technique of Bubble Sort to perform the sorting. We have tried to access the second element of the sublists using the nested loops. This performs the in-place method of sorting. The time complexity is similar to the Bubble Sort i.e., O(n^2) 

Python3




# Python code to sort the lists using the second element
# of sublists inplace way to sort, use of third variable
def Sort(sub_li):
   
    l = len(sub_li)
     
    for i in range(0, l):
        for j in range(0, l-i-1):
             
            if (sub_li[j][1] > sub_li[j + 1][1]):
                tempo = sub_li[j]
                sub_li[j] = sub_li[j + 1]
                sub_li[j + 1] = tempo
     
    return sub_li
 
# Input list
sub_li = [['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]
 
# Printing the list
print(Sort(sub_li))


Output:

[['akash', 5], ['rishav', 10], ['gaurav', 15], ['ram', 20]]

Time Complexity: O(n*n),  where n is the length of the given sub_li.
Auxiliary Space: O(1)

Method 2: Sorting by the use of sort() method 

While sorting via this method the actual content of the tuple is changed, and just like the previous method, an in-place method of sort is performed.

Python3




# Python code to sort the tuples using second element
# of sublist Inplace way to sort using sort()
def Sort(sub_li):
 
    # reverse = None (Sorts in Ascending order)
    # key is set to sort using second element of
    # sublist lambda has been used
    sub_li.sort(key = lambda x: x[1])
    return sub_li
 
# Input list
sub_li =[['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]
 
# Printing the sub list
print(Sort(sub_li))


Output

[['akash', 5], ['rishav', 10], ['gaurav', 15], ['ram', 20]]

Time complexity: O(n*logn)
Auxiliary space: O(1) as the sorting is performed in place using the sort() function. The sort() function has a time complexity of O(nlogn) for the average and worst-case scenarios.

Method 3: Sorting by the use of sorted() method 

Sorted() sorts a list and always returns a list with the elements in a sorted manner, without modifying the original sequence. It takes three parameters of which two are optional, here we tried to use all three:

  • Iterable : sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted.
  • Key(optional): A function that would serve as a key or a basis of sort comparison.
  • Reverse(optional): To sort this in ascending order we could have just ignored the third parameter, which we did in this program. If set true, then the iterable would be sorted in reverse (descending) order, by default it is set as false.

Python3




# Python code to sort the tuples using second element
# of sublist Function to sort using sorted()
def Sort(sub_li):
 
    # reverse = None (Sorts in Ascending order)
    # key is set to sort using second element of
    # sublist lambda has been used
    return(sorted(sub_li, key=lambda x: x[1]))
 
# Input list
sub_li = [['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]
 
# Printing resultant list
print(Sort(sub_li))


Output

[['akash', 5], ['rishav', 10], ['gaurav', 15], ['ram', 20]]

Time complexity: O(n log n) where ‘n’ is the number of elements in the list. This is because the sorting is done using the built-in Python function sorted() which has a time complexity of O(n log n) in the average and worst case.
Auxiliary space: O(n) because a new list is created and returned by the sorted() function which has the same number of elements as the input list.

Method 4: Use orderedDIct

Python3




from collections import OrderedDict
 
def Sort(sub_li):
    # create an ordered dictionary
    sub_li_dict = OrderedDict()
    for i in sub_li:
        sub_li_dict[i[1]] = i
     
    # sorting the dictionary by key
    sorted_dict = sorted(sub_li_dict.items())
    # extracting the values from the sorted dictionary
    sort_sub_li = [value for key, value in sorted_dict]
     
    return sort_sub_li
   
# Driver Code
sub_li =[['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]
print(Sort(sub_li))


Output

[['akash', 5], ['rishav', 10], ['gaurav', 15], ['ram', 20]]

The above approach implements an ordered dictionary that stores the sublist element as key-value pairs. The dictionary is then sorted by the keys and the list is returned with the elements sorted according to the second element in the sublist.

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

Method 4: Using itemgetter() function from the operator module:

  1. We first import the itemgetter() function from the operator module. This function is used to retrieve the elements of a tuple based on their index.
  2. We define the sort_tuples() function that takes a list of sublists as input.
  3. Inside the function, we use the key parameter of the sorted() function to specify the sorting criteria. We pass itemgetter(1) as the key, which returns a function that retrieves the second element of a tuple.
  4. Finally, we call the sorted() function with the input list sub_li and return the sorted list.

Python3




from operator import itemgetter
 
 
def sort_tuples(sub_li):
 
    # itemgetter(1) returns a function that can be used to retrieve the
    # second element of a tuple (i.e., the element at index 1)
    # this function is used as the key for sorting the sublists
    return sorted(sub_li, key=itemgetter(1))
 
 
# Input list
sub_li = [['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]
 
# Printing resultant list
print(sort_tuples(sub_li))


Output

[['akash', 5], ['rishav', 10], ['gaurav', 15], ['ram', 20]]

Time complexity: O(n log n), where n is the number of sublists in the input list. This is because the sorted() function uses a variant of the Merge Sort algorithm, which has a worst-case time complexity of O(n log n).
Auxiliary space: O(n), where n is the number of sublists in the input list. 

Method 5: Using numpy’s argsort():

Note: install numpy module using command “pip install numpy”

Algorithm:

  1. Create an input list of sublists.
  2. Convert the list to a NumPy array.
  3. Extract the second column of the array and convert it to integers.
  4. Sort the array based on the second column using the argsort() method.
  5. Convert the sorted array back to a list.
  6. Print the sorted list.

Python3




import numpy as np
 
# Define the input list
sub_li = [['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]
 
# Converting the list to a NumPy array
sub_arr = np.array(sub_li)
 
# Extracting the second column and convert it to integers
values = sub_arr[:, 1].astype(int)
 
# Sort the array by the second column (index 1)
sorted_arr = sub_arr[values.argsort()]
 
# Converting the sorted array back to a list
sorted_li = sorted_arr.tolist()
 
# Printing sorted list
print(sorted_li)


Output:

[['akash', '5'], ['rishav', '10'], ['gaurav', '15'], ['ram', '20']]

Time complexity: O(N log N), where n is the number of sublists in the input list. The sorting operation is the most time-consuming operation and has a time complexity of O(n log n).

Auxiliary Space: O(N), where n is the number of sublists in the input list. The space complexity is dominated by the NumPy array created from the input list.

Method#6: Using the Recursive method.

  1. Define a `merge()` function that takes in two lists (`left` and `right`) and merges them while sorting based on the second element of the sublists.
  2. In the `merge()` function, initialize an empty list `result` to store the merged and sorted sublists.
  3. Initialize two pointers `i` and `j` to 0, representing the current index in `left` and `right` respectively.
  4. Compare the second element of the sublists at `left[i]` and `right[j]`.
  5. If the second element of `left[i]` is less than or equal to the second element of `right[j]`, append `left[i]` to `result` and increment `i`.
  6. Otherwise, append `right[j]` to `result` and increment `j`.
  7. Repeat steps 4-6 until either `left` or `right` is exhausted.
  8. Append the remaining elements in `left` and `right` to `result` if any.
  9. Return `result` as the merged and sorted list.

Python3




def merge(left, right):
 
    # Empty list to store merge and sorted list
    result = []
 
    i = 0
    j = 0
 
    while i < len(left) and j < len(right):
 
    if left[i][1] <= right[j][1]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
     
    result.extend(left[i:])
    result.extend(right[j:])
     
    return result
 
# Recursive function to sort sub list
def sort_recursive(sub_li):
 
  if len(sub_li) <= 1:
        return sub_li
     
    mid = len(sub_li) // 2
    left = sub_li[:mid]
    right = sub_li[mid:]
    left = sort_recursive(left)
    right = sort_recursive(right)
     
    return merge(left, right)
 
# Input sub list
sub_li = [['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]
 
# Calling function and printing sub list
print(sort_recursive(sub_li))


Output

[['akash', 5], ['rishav', 10], ['gaurav', 15], ['ram', 20]]

Time Complexity: O(N logN)
The time complexity of the merge sort algorithm is O(n log n), where n is the length of the input list `sub_li`. This is because the list is recursively divided into halves until the base case of a single element or an empty list is reached, and then merged back up the recursion tree while sorting, taking log n levels. At each level, the merging operation takes O(n) time.

Auxiliary Space: O(1)
The space complexity of the merge sort algorithm is O(n), where n is the length of the input list `sub_li`. This is because additional space is required to store the merged and sorted sublists during the merging operation. However, this implementation uses an in-place merge operation that does not require additional space, so the space complexity is effectively O(1).


Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Last Updated : 09 May, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials