Python | Sort tuple list on basis of difference of elements
Last Updated :
27 Apr, 2023
Sometimes, while working with data, we can have a problem of sorting them. There are many types of basis on which sorting can be performed. But this article discusses sorting on basis of difference of both elements of pair. Let's discuss certain ways in which this can be done.
Method #1 : Using sorted() + lambda The combination of above functionalities can be used to solve this problem. In this, sorting is performed by sorted() and lambda function is fed as key to perform desired sorting.
Python3
# Python3 code to demonstrate working of
# Sort tuple list on basis of difference of elements
# using sorted() + lambda
# initialize list
test_list = [(1, 4), (6, 5), (8, 10)]
# printing original list
print("The original list : " + str(test_list))
# Sort tuple list on basis of difference of elements
# using sorted() + lambda
res = sorted(test_list, key = lambda sub: abs(sub[1] - sub[0]))
# printing result
print("List after sorting by difference : " + str(res))
Output : The original list : [(1, 4), (6, 5), (8, 10)]
List after sorting by difference : [(6, 5), (8, 10), (1, 4)]
Time Complexity: O(nlogn), where n is the length of the input list. This is because we’re using sorted() + lambda which has a time complexity of O(nlogn) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.
Method #2 : Using sort() + comparator + cmp() This is yet another way to perform this task. In this, we pass the sort(), a comparator function which performs the similar difference logic using cmp(). Works only in Python2.
Python
# Python code to demonstrate working of
# Sort tuple list on basis of difference of elements
# using sort() + comparator + cmp()
# comparator function
def diff_sort(ele1, ele2):
return cmp(ele2[0] - ele2[1], ele1[0] - ele1[1])
# initialize list
test_list = [(1, 4), (6, 5), (8, 10)]
# printing original list
print("The original list : " + str(test_list))
# Sort tuple list on basis of difference of elements
# using sort() + comparator + cmp()
test_list.sort(diff_sort)
# printing result
print("List after sorting by difference : " + str(test_list))
Output : The original list : [(1, 4), (6, 5), (8, 10)]
List after sorting by difference : [(6, 5), (8, 10), (1, 4)]
Time Complexity: O(n*nlogn), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #3 : Using itemgetter
In this, we import the itemgetter function from the operator module. The itemgetter function takes an index as input and returns a function that retrieves that index from a tuple. We then use the itemgetter function to retrieve the first and second elements of each tuple and calculate their absolute difference. Finally, we pass the lambda function as the key for the sorted function to sort the list based on the difference between the elements of each tuple. The resulting sorted list is then printed to the console.
Python3
from operator import itemgetter
# Original list of tuples
original_list = [(1, 4), (6, 5), (8, 10)]
# Sort the list by difference using itemgetter as key
sorted_list = sorted(original_list, key=lambda x: abs(itemgetter(0)(x) - itemgetter(1)(x)))
# Print the sorted list
print("List after sorting by difference:", sorted_list)
OutputList after sorting by difference: [(6, 5), (8, 10), (1, 4)]
The complexity analysis of the code is as follows:
Defining the original list of tuples:
This step takes O(n) time, where n is the size of the original list.
Sorting the list by difference using itemgetter as key:
Sorting takes O(nlogn) time in the worst case, where n is the size of the original list. Since we are sorting based on the difference between the first and second elements of each tuple, the time complexity of each comparison operation between the elements of the list is O(1). Therefore, the overall time complexity of the sorting operation in this code is O(nlogn).
Printing the sorted list:
This step takes O(n) time, where n is the size of the sorted list.
time complexity: O(nlogn)
Method #4: using the heapq module:
Algorithm:
1.Create a heap of tuples, where each tuple contains the difference between the two elements of the input tuple and the input tuple itself.
2.Heapify the created heap.
3.Pop the elements from the heap and add them to the output list until the heap is empty.
Python3
import heapq
# initialize list
test_list = [(1, 4), (6, 5), (8, 10)]
# printing original list
print("The original list : " + str(test_list))
# Sort tuple list on basis of difference of elements
# using heapq module
heap = [((ele[1]-ele[0]), ele) for ele in test_list]
heapq.heapify(heap)
test_list = [heapq.heappop(heap)[1] for i in range(len(heap))]
# printing result
print("List after sorting by difference : " + str(test_list))
#This code is contributed by Jyothi pinjala
OutputThe original list : [(1, 4), (6, 5), (8, 10)]
List after sorting by difference : [(6, 5), (8, 10), (1, 4)]
Time Complexity:
The time complexity of creating the heap is O(n), where n is the number of tuples in the input list. The time complexity of heapifying the heap is O(nlogn). The time complexity of popping the elements from the heap is O(nlogn). Therefore, the overall time complexity is O(nlogn).
Space Complexity:
The space complexity of creating the heap is O(n), where n is the number of tuples in the input list. The space complexity of heapifying the heap is O(1). The space complexity of popping the elements from the heap is O(1). Therefore, the overall space complexity is O(n).
Similar Reads
Python | Sort tuple based on occurrence of first element
Given a list of tuples, write a Python program to sort the list based on the occurrence of first element of tuples. Examples: Input : [(1, 'Jake'), (2, 'Bob'), (1, 'Cara')] Output : [(1, 'Jake', 'Cara', 2), (2, 'Bob', 1)] Input : [('b', 'ball'), ('a', 'arm'), ('b', 'b'), ('a', 'ant')] Output : [('a'
3 min read
Python - Sort List items on basis of their Digits
Given List of elements, perform sorting on basis of digits of numbers. Input : test_list = [434, 211, 12, 3] Output : [12, 211, 3, 434] Explanation : 3 < 12, still later in list, as initial digit, 1 < 3. Hence sorted by digits rather than number. Input : test_list = [534, 211, 12, 7] Output :
2 min read
Python - Sort Tuple List by Nth Element of Tuple
We are given list of tuple we need to sort tuple by Nth element of each tuple. For example d = [(1, 5), (3, 2), (2, 8), (4, 1)] and k=1 we need to sort by 1st element of each tuple so that output for given list should be [(4, 1), (3, 2), (1, 5), (2, 8)]Using sorted() with lambdasorted() function wit
3 min read
Python - Assign K to Non Max-Min elements in Tuple
Sometimes, while working with Python data, we can have a problem in which we need to assign particular value as per certain condition. One of condition can be non-max, min element. This kind of task can occur in many application of day-day programming and competitive programming. Lets discuss certai
7 min read
Python - Check if all tuples have element difference less than K
Given a Tuple list, check if each tuple has a difference less than K. Input : test_list = [(3, 4), (1, 2), (7, 8), (9, 13)], K = 2 Output : False Explanation : 13 - 9 = 4 > 2. Input : test_list = [(3, 4), (1, 2), (7, 8)], K = 2Output : True Explanation : All have abs. diff 1 < 2. Method #1 :
7 min read
Python | Set Difference in list of dictionaries
The difference of two lists have been discussed many times, but sometimes we have a large number of data and we need to find the difference i.e the elements in dict2 not in 1 to reduce the redundancies. Let's discuss certain ways in which this can be done. Method #1 : Using list comprehension The na
3 min read
Python Program to Sort Matrix Rows by summation of consecutive difference of elements
Given a Matrix, the following article depicts how to sort rows of a matrix on the basis of summation of difference between consecutive elements of a row. Input : test_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]], Output : [[4, 3, 2, 1], [7, 2, 4, 5], [1, 5, 3, 6], [6, 9, 3, 2]] Ex
7 min read
Difference between List VS Set VS Tuple in Python
In Python, Lists, Sets and Tuples store collections but differ in behavior. Lists are ordered, mutable and allow duplicates, suitable for dynamic data. Sets are unordered, mutable and unique, while Tuples are ordered, immutable and allow duplicates, ideal for fixed data. List in PythonA List is a co
2 min read
Sort Tuple of Lists in Python
The task of sorting a tuple of lists involves iterating through each list inside the tuple and sorting its elements. Since tuples are immutable, we cannot modify them directly, so we must create a new tuple containing the sorted lists. For example, given a tuple of lists a = ([2, 1, 5], [1, 5, 7], [
3 min read
Python - Alternate Elements operation on Tuple
Sometimes, while working with Python Tuples, we can have problem in which we need to perform operations of extracted alternate chains of tuples. This kind of operation can have application in many domains such as web development. Lets discuss certain ways in which this task can be performed. Input :
5 min read