Open In App

Python | Sort tuple list by Nth element of tuple

Last Updated : 08 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python list, we can come across a problem in which we need to sort the list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let’s discuss certain ways in which this task can be performed. 

Method #1: Using sort() + lambda The combination of above functions can be used to perform this task. In this, we just pass a lambda function to sort() with an appropriate tuple element index according to which sort has to be performed. 

Step-by-step approach:

  • Set the value of variable N to 1.
  • Use the sort() method to sort the list of tuples test_list based on the Nth element of each tuple.
  • The sorting is done using the lambda function which takes each tuple as its argument and returns the Nth element of the tuple.
  • Print the sorted list of tuples test_list.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Sort tuple list by Nth element of tuple
# using sort() + lambda
 
# initializing list
test_list = [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# index according to which sort to perform
N = 1
 
# Sort tuple list by Nth element of tuple
# using sort() + lambda
test_list.sort(key = lambda x: x[N])
 
# printing result
print("List after sorting tuple by Nth index sort : " + str(test_list))


Output

The original list is : [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)]
List after sorting tuple by Nth index sort : [(6, 1, 5), (6, 2, 4), (7, 4, 2), (4, 5, 1)]

Time Complexity: O(n*logn)
Auxiliary Space: O(1)

Method #2: Using sort() + itemgetter() This is similar to the above method. The difference is just that we use itemgetter(), to perform this task that is done by lambda in the above method. 

Step-by-step approach:

  • It initializes the variable N to a value of 1, indicating that we want to sort the list based on the second element of each tuple.
  • It uses the sort() method of the test_list object and passes in the key argument, which is set to the itemgetter(N) function. This means that the sort() method will sort the list based on the element at the Nth index of each tuple.
  • It prints the sorted list using the print() function and string concatenation.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Sort tuple list by Nth element of tuple
# using sort() + itemgetter()
from operator import itemgetter
 
# initializing list
test_list = [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# index according to which sort to perform
N = 1
 
# Sort tuple list by Nth element of tuple
# using sort() + itemgetter()
test_list.sort(key = itemgetter(N))
 
# printing result
print("List after sorting tuple by Nth index sort : " + str(test_list))


Output

The original list is : [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)]
List after sorting tuple by Nth index sort : [(6, 1, 5), (6, 2, 4), (7, 4, 2), (4, 5, 1)]

Time Complexity: O(n log n) – Sorting the list using sort() method.
Auxiliary Space: O(1) – No extra space is used.

Method #3:  using sorted and custom function

Python3




# Python3 code to demonstrate working of
# Sort tuple list by Nth element of tuple
# using sorted() and custom function
 
# custom sorting function
def sort_by_nth_element(tup):
    return tup[N]
 
# initializing list
test_list = [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# index according to which sort to perform
N = 1
 
# Sort tuple list by Nth element of tuple using sorted() and custom function
sorted_list = sorted(test_list, key = sort_by_nth_element)
 
# printing result
print("List after sorting tuple by Nth index sort : " + str(sorted_list))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original list is : [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)]
List after sorting tuple by Nth index sort : [(6, 1, 5), (6, 2, 4), (7, 4, 2), (4, 5, 1)]

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

Method #4:  using Bubble sort algorithm

It is a simple sorting algorithm, In this we use a flag variable to keep track of any swaps made during a pass of the outer loop if no swaps were made the list is already sorted and the loop can be broken.

Python3




test_list = [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)]
N=1
print("The original list:",test_list )
# initialize the flag variable to indicate if any swap has been made
flag = True
 
# while loop runs until no more swaps are made
while flag:
    # reset the flag variable
    flag = False
    # outer for loop iterates through the elements in the list
    for i in range(len(test_list ) - 1):
        # inner for loop starts from next element of outer for loop and compare with outer for loop element
        for j in range(i+1, len(test_list )):
            # check if second element in the tuple of the first element is less than the second element in the tuple of the next element
            if test_list [i][N] < test_list [j][N]:
                # swap the elements
                test_list [i], test_list [j] = test_list [j], test_list[i]
                # set the flag variable to indicate that a swap has been made
                flag = True
# print the sorted list
print("Sorted list:", test_list )


Output

The original list: [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)]
Sorted list: [(4, 5, 1), (7, 4, 2), (6, 2, 4), (6, 1, 5)]

Time complexity : O(n^2) 
Auxiliary Space: O(1)

Method 5: Using the heapq.nsmallest() function

This approach uses the heapq.nsmallest() function to return a sorted list of tuples. The nsmallest() function takes three arguments: n, the number of smallest elements to return (in this case, the length of the list); iterable, the list of tuples to sort; and key, a function that returns the value of the Nth element of each tuple. The resulting sorted list is assigned to the sorted_list variable.

Python3




import heapq
 
# initializing list
test_list = [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# index according to which sort to perform
N = 1
 
# Sort tuple list by Nth element of tuple
sorted_list = heapq.nsmallest(len(test_list), test_list, key=lambda x: x[N])
 
# printing result
print("List after sorting tuple by Nth index sort : " + str(sorted_list))


Output

The original list is : [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)]
List after sorting tuple by Nth index sort : [(6, 1, 5), (6, 2, 4), (7, 4, 2), (4, 5, 1)]

Time complexity: O(n log n), where n is the length of the input list, because it uses a heap to sort the list.
Auxiliary space: O(n), because it creates a new sorted list.

Method#6: Using Recursive method.

Algorithm:

  1. Define a function called sort_tuple_by_nth_index which takes a list called test_list and an integer called N as input.
  2. Check if the length of the list is 1 or less, return the list as it is already sorted.
  3. Otherwise, set the pivot as the Nth element of the first element in the list.
  4. Create two sublists, one containing elements less than or equal to the pivot and the other containing elements greater than the pivot.
  5. Recursively sort the two sublists by calling the sort_tuple_by_nth_index function on them.
  6. Concatenate the sorted sublists with the first element of the original list in the middle.
  7. Return the sorted list.

Python3




def sort_tuple_by_nth_index(test_list, N):
    # base case: if the length of the list is 1 or less, it is already sorted
    if len(test_list) <= 1:
        return test_list
     
    # recursive case:
    # divide the list into two sublists, one containing elements less than or equal to the Nth element of the first element
    # and the other containing elements greater than the Nth element of the first element
    pivot = test_list[0][N]
    less_than_or_equal = [t for t in test_list[1:] if t[N] <= pivot]
    greater_than = [t for t in test_list[1:] if t[N] > pivot]
     
    # recursively sort the two sublists
    sorted_less_than_or_equal = sort_tuple_by_nth_index(less_than_or_equal, N)
    sorted_greater_than = sort_tuple_by_nth_index(greater_than, N)
     
    # return the sorted concatenation of the two sublists
    return sorted_less_than_or_equal + [test_list[0]] + sorted_greater_than
test_list = [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)]
N = 1
print("The original list:", test_list)
sorted_list = sort_tuple_by_nth_index(test_list, N)
print("List after sorting tuple by Nth index sort:", sorted_list)


Output

The original list: [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)]
List after sorting tuple by Nth index sort: [(6, 1, 5), (6, 2, 4), (7, 4, 2), (4, 5, 1)]

The time complexity of the algorithm is O(nlogn) in the average and worst-case scenarios. This is because the algorithm uses a divide-and-conquer strategy, dividing the list into sublists and sorting them recursively. 

The space complexity of the algorithm is O(n) due to the recursion stack. However, the worst-case scenario for space complexity is O(n^2) if the algorithm encounters a very unbalanced split of the input list at each recursive call.



Similar Reads

Python | Replace tuple according to Nth tuple element
Sometimes, while working with data, we might have a problem in which we need to replace the entry in which a particular entry of data is matching. This can be a matching phone no, id etc. This has it's application in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + enumerate() This task
8 min read
Python - Extract Kth element of every Nth tuple in List
Given list of tuples, extract Kth column element of every Nth tuple. Input :test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6, 4, 7), (2, 5, 7), (1, 9, 10), (3, 5, 7)], K = 2, N = 3 Output : [3, 8, 10] Explanation : From 0th, 3rd, and 6th tuple, 2nd elements are 3, 8, 10. Input :test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6,
8 min read
Python | Counting Nth tuple element
Sometimes, while working with Python, we can have a problem in which we need to count the occurrence of a particular's elements. This kind of problem is quite common while working with records. Let's discuss a way in which this task can be performed. Method #1 : Using Counter() + generator expression The combination of above functionalities can be
5 min read
Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple
The task is to write a Python Program to sort a list of tuples in increasing order by the last element in each tuple. Input: [(1, 3), (3, 2), (2, 1)] Output: [(2, 1), (3, 2), (1, 3)] Explanation: sort tuple based on the last digit of each tuple. Methods #1: Using sorted(). Sorted() method sorts a list and always returns a list with the elements in
7 min read
Python - Sort by Frequency of second element in Tuple List
Given list of tuples, sort by frequency of second element of tuple. Input : test_list = [(6, 5), (1, 7), (2, 5), (8, 7), (9, 8), (3, 7)] Output : [(1, 7), (8, 7), (3, 7), (6, 5), (2, 5), (9, 8)] Explanation : 7 occurs 3 times as 2nd element, hence all tuples with 7, are aligned first. Input : test_list = [(1, 7), (8, 7), (9, 8), (3, 7)] Output : [(
6 min read
Python | Insert Nth element to Kth element in other list
Sometimes, while working with Python list, there can be a problem in which we need to perform the inter-list shifts of elements. Having a solution to this problem is always very useful. Let’s discuss the certain way in which this task can be performed. Method 1: Using pop() + insert() + index() This particular task can be performed using a combinat
9 min read
Python | Minimum K records of Nth index in tuple list
Sometimes, while working with data, we can have a problem in which we need to get the minimum of elements filtered by the Nth element of record. This has a very important utility in web development domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using filter() + lambda + set() + list comprehension The combination
9 min read
Python - Get maximum of Nth column from tuple list
Sometimes, while working with Python lists, we can have a task in which we need to work with tuple list and get the maximum of its Nth index. This problem has application in web development domain while working with data information. Let’s discuss certain ways in which this task can be performed. Method #1: Using list comprehension + max() This tas
7 min read
Python - Flatten tuple of List to tuple
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have listed as their constituent elements. This kind of problem is common in data domains such as Machine Learning. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ([5], [6], [3], [8]) O
7 min read
Python Program to Convert Tuple Matrix to Tuple List
Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]] Output : [(4, 10), (5, 13)] Explanation : All co
8 min read