Open In App

Python program to Sort Tuples by their Maximum element

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

Given a Tuple List sort tuples by maximum element in a tuple.

Input : test_list = [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)] 
Output : [(19, 4, 5, 3), (4, 5, 5, 7), (1, 3, 7, 4), (1, 2)] 
Explanation : 19 > 7 = 7 > 2, is order, hence reverse sorted by maximum element.

Input : test_list = [(4, 5, 5, 7), (19, 4, 5, 3), (1, 2)] 
Output : [(19, 4, 5, 3), (4, 5, 5, 7), (1, 2)] 
Explanation : 19 > 7 > 2, is order, hence reverse sorted by maximum element. 

Method #1 : Using max() + sort()

In this, we perform task of getting maximum element in tuple using max(), and sort() operation is used to perform sort.

Python3




# Python3 code to demonstrate working of
# Sort Tuples by Maximum element
# Using max() + sort()
 
# helper function
def get_max(sub):
    return max(sub)
 
# initializing list
test_list = [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# sort() is used to get sorted result
# reverse for sorting by max - first element's tuples
test_list.sort(key = get_max, reverse = True)
 
# printing result
print("Sorted Tuples : " + str(test_list))


Output:

The original list is : [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)] Sorted Tuples : [(19, 4, 5, 3), (4, 5, 5, 7), (1, 3, 7, 4), (1, 2)]

Time Complexity: O(n*nlogn) where n is the number of elements in the list “test_list”.  max() + sort() performs n*nlogn number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list

Method #2 : Using sort() + lambda + reverse

In this, we use similar functionality, the only difference here being use of lambda fnc. rather than external function for task of getting reverse sorting.

Python3




# Python3 code to demonstrate working of
# Sort Tuples by Maximum element
# Using sort() + lambda + reverse
 
# initializing list
test_list = [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# lambda function getting maximum elements
# reverse for sorting by max - first element's tuples
test_list.sort(key = lambda sub : max(sub), reverse = True)
 
# printing result
print("Sorted Tuples : " + str(test_list))


Output:

The original list is : [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)] Sorted Tuples : [(19, 4, 5, 3), (4, 5, 5, 7), (1, 3, 7, 4), (1, 2)]

Method #3: Using a loop to find the maximum element and sort based on it

  • Initialize an empty list “sorted_list”.
  • Initialize a variable “max_val” to 0.
  • Loop through each tuple in the original list “test_list”.
  • Within the loop, find the maximum value in the tuple using the max() function and assign it to “max_val”.
  • Append a tuple of the original tuple and “max_val” to “sorted_list”.
  • Sort “sorted_list” in descending order based on the “max_val” value in each tuple.
  • Create a new list “final_list” with just the original tuples from “sorted_list”.
  • Print “final_list”.

Python3




# initializing list
test_list = [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using a loop to find the maximum element and sort based on it
sorted_list = []
max_val = 0
for tup in test_list:
    max_val = max(tup)
    sorted_list.append((tup, max_val))
sorted_list.sort(key=lambda x: x[1], reverse=True)
final_list = [tup[0] for tup in sorted_list]
 
# printing result
print("Sorted Tuples : " + str(final_list))


Output

The original list is : [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)]
Sorted Tuples : [(19, 4, 5, 3), (4, 5, 5, 7), (1, 3, 7, 4), (1, 2)]

Time complexity: O(nlogn) – sorting takes O(nlogn) time, and the loop takes O(n) time, where n is the length of the input list.
Auxiliary space: O(n) – we are creating a new list with n tuples.

Method #6: Using Heapq module

Step-by-step approach:

  • Import the heapq module.
  • Initialize an empty list called max_values.
  • Use a for loop to iterate over each tuple in the test_list.
  • Use the nlargest() function from the heapq module to find the maximum value in the tuple.
  • Append the maximum value to the max_values list.
  • Use the zip() function to combine the test_list and max_values list into a new list of tuples.
  • Use the sorted() function to sort the new list of tuples based on the second element (i.e., the maximum value).
  • Use a list comprehension to extract the first element of each tuple in the sorted list and assign it to a variable called final_list.
  • Print the final_list.

Python3




import heapq
 
# initializing list
test_list = [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using heapq to find the maximum element and sort based on it
max_values = []
for tup in test_list:
    max_values.append(heapq.nlargest(1, tup)[0])
new_list = list(zip(test_list, max_values))
sorted_list = sorted(new_list, key=lambda x: x[1], reverse=True)
final_list = [tup[0] for tup in sorted_list]
 
# printing result
print("Sorted Tuples : " + str(final_list))


Output

The original list is : [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)]
Sorted Tuples : [(19, 4, 5, 3), (4, 5, 5, 7), (1, 3, 7, 4), (1, 2)]

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



Similar Reads

Python program to sort tuples by frequency of their absolute difference
Given a list of dual tuples, the task here is to write a Python program that can sort them by the frequency of their elements' absolute differences. Input : [(1, 6), (11, 3), (9, 1), (6, 11), (2, 10), (5, 7)] Output : [(5, 7), (1, 6), (6, 11), (11, 3), (9, 1), (2, 10)] Explanation : 7 - 5 = 2 occurs only 1 time. 5 occurs twice [( 6 - 1), (11 - 6)]
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 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
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 | 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 | 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