Open In App

Python | Custom sorting in list of tuples

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

Sometimes, while working with list of tuples, we can have a problem in which we need to perform it’s sorting. Naive sorting is easier, but sometimes, we have to perform custom sorting, i.e by decreasing order of first element and increasing order of 2nd element. And these can also be in cases of different types of tuples. Let’s discuss certain cases and solutions to perform this kind of custom sorting. 

Method #1 : Using sorted() + lambda This task can be performed using the combination of above functions. In this, we just perform the normal sort, but in addition we feed a lambda function which handles the case of custom sorting discussed above. 

Python3




# Python3 code to demonstrate working of
# Custom sorting in list of tuples
# Using sorted() + lambda
 
# Initializing list
test_list = [(7, 8), (5, 6), (7, 5), (10, 4), (10, 1)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Custom sorting in list of tuples
# Using sorted() + lambda
res = sorted(test_list, key = lambda sub: (-sub[0], sub[1]))
 
# printing result
print("The tuple after custom sorting is : " + str(res))


Output : 

The original list is : [(7, 8), (5, 6), (7, 5), (10, 4), (10, 1)]
The tuple after custom sorting is : [(10, 1), (10, 4), (7, 5), (7, 8), (5, 6)]

Time Complexity: O(n*nlogn), where n is the length of the list test_list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list 

  Method #2 : Using sorted() + lambda() + sum() ( With sum of tuple condition) In this method, similar solution sustains. But the case here is that we have tuple as the 2nd element of tuple and its sum has to considered for sort order. Other functions than summation can be extended in similar solution. 

Python3




# Python3 code to demonstrate working of
# Custom sorting in list of tuples
# Using sorted() + lambda() + sum()
 
# Initializing list
test_list = [(7, (8, 4)), (5, (6, 1)), (7, (5, 3)), (10, (5, 4)), (10, (1, 3))]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Custom sorting in list of tuples
# Using sorted() + lambda() + sum()
res = sorted(test_list, key = lambda sub: (-sub[0], sum(sub[1])))
 
# printing result
print("The tuple after custom sorting is : " + str(res))


Output : 

The original list is : [(7, (8, 4)), (5, (6, 1)), (7, (5, 3)), (10, (5, 4)), (10, (1, 3))]
The tuple after custom sorting is : [(10, (1, 3)), (10, (5, 4)), (7, (5, 3)), (7, (8, 4)), (5, (6, 1))]

Using Bubble sort:

Approach:

  • Initialize the list to be sorted.
  • Find the length of the list.
  • Loop through each element of the list.
  • Within the outer loop, loop through each element of the list from 0 to n-i-1.
  • Compare the first elements of the current and next tuples. If the first element of the next tuple is greater than the first element of the current tuple, swap the positions of the current and next tuples.
  • If the first elements of the current and next tuples are equal, compare the second elements of the current and next tuples. If the second element of the current tuple is greater than the second element of the next tuple, swap the positions of the current and next tuples.
  • After all iterations, the list will be sorted in descending order based on the first element of the tuples, and in ascending order based on the second element of the tuples.

Python3




lst = [(7, 8), (5, 6), (7, 5), (10, 4), (10, 1)]
n = len(lst)
 
for i in range(n):
    for j in range(n-i-1):
        if lst[j][0] < lst[j+1][0] or (lst[j][0] == lst[j+1][0] and lst[j][1] > lst[j+1][1]):
            lst[j], lst[j+1] = lst[j+1], lst[j]
 
print(lst)


Output

[(10, 1), (10, 4), (7, 5), (7, 8), (5, 6)]

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



Similar Reads

Python | Remove duplicate tuples from list of tuples
Given a list of tuples, Write a Python program to remove all the duplicated tuples from the given list. Examples: Input : [(1, 2), (5, 7), (3, 6), (1, 2)] Output : [(1, 2), (5, 7), (3, 6)] Input : [('a', 'z'), ('a', 'x'), ('z', 'x'), ('a', 'x'), ('z', 'x')] Output : [('a', 'z'), ('a', 'x'), ('z', 'x')] Method #1 : List comprehension This is a naive
5 min read
Python | Find the tuples containing the given element from a list of tuples
Given a list of tuples, the task is to find all those tuples containing the given element, say n. Examples: Input: n = 11, list = [(11, 22), (33, 55), (55, 77), (11, 44)] Output: [(11, 22), (11, 44)] Input: n = 3, list = [(14, 3),(23, 41),(33, 62),(1, 3),(3, 3)] Output: [(14, 3), (1, 3), (3, 3)] There are multiple ways we can find the tuples contai
6 min read
Python | Remove tuples from list of tuples if greater than n
Given a list of a tuple, the task is to remove all the tuples from list, if it's greater than n (say 100). Let's discuss a few methods for the same. Method #1: Using lambda STEPS: Initialize a list of tuples: ini_tuple = [('b', 100), ('c', 200), ('c', 45), ('d', 876), ('e', 75)]Print the initial list: print("intial_list", str(ini_tuple))Define the
6 min read
Python | Remove tuples having duplicate first value from given list of tuples
Given a list of tuples, the task is to remove all tuples having duplicate first values from the given list of tuples. Examples: Input: [(12.121, 'Tuple1'), (12.121, 'Tuple2'), (12.121, 'Tuple3'), (923232.2323, 'Tuple4')] Output: [(12.121, 'Tuple1'), (923232.2323, 'Tuple4')]Input: [('Tuple1', 121), ('Tuple2', 125), ('Tuple1', 135), ('Tuple4', 478)]
7 min read
Python | Count tuples occurrence in list of tuples
Many a time while developing web and desktop products in Python, we use nested lists and have several queries about how to find the count of unique tuples. Let us see how to get the count of unique tuples in the given list of tuples. Below are some ways to achieve the above task. Method #1: Using Iteration C/C++ Code # Python code to count unique #
5 min read
Python | Combining tuples in list of tuples
Sometimes, we might have to perform certain problems related to tuples in which we need to segregate the tuple elements to combine with each element of complex tuple element( such as list ). This can have application in situations we need to combine values to form a whole. Let's discuss certain ways in which this can be performed. Method #1: Using
7 min read
Python | Convert string tuples to list tuples
Sometimes, while working with Python we can have a problem in which we have a list of records in form of tuples in stringified form and we desire to convert them to a list of tuples. This kind of problem can have its occurrence in the data science domain. Let's discuss certain ways in which this task can be performed. Method 1 (Using eval() + list
4 min read
Python - Filter all uppercase characters Tuples from given list of tuples
Given a Tuple list, filter tuples that contain all uppercase characters. Input : test_list = [("GFG", "IS", "BEST"), ("GFg", "AVERAGE"), ("GfG", ), ("Gfg", "CS")] Output : [('GFG', 'IS', 'BEST')] Explanation : Only 1 tuple has all uppercase Strings. Input : test_list = [("GFG", "iS", "BEST"), ("GFg", "AVERAGE"), ("GfG", ), ("Gfg", "CS")] Output : [
8 min read
Python program to find Tuples with positive elements in List of tuples
Given a list of tuples. The task is to get all the tuples that have all positive elements. Examples: Input : test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)] Output : [(4, 5, 9)] Explanation : Extracted tuples with all positive elements. Input : test_list = [(-4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)] Output : [] Explanation : No tuple wit
10 min read
Python program to find tuples which have all elements divisible by K from a list of tuples
Given a list of tuples. The task is to extract all tuples which have all elements divisible by K. Input : test_list = [(6, 24, 12), (60, 12, 6), (12, 18, 21)], K = 6 Output : [(6, 24, 12), (60, 12, 6)] Explanation : Both tuples have all elements multiple of 6. Input : test_list = [(6, 24, 12), (60, 10, 5), (12, 18, 21)], K = 5 Output : [(60, 10, 5)
7 min read