Python program to Sort Tuples by their Maximum element
Last Updated :
15 May, 2023
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))
OutputThe 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))
OutputThe 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 Matrix by Maximum Row element
Given a Matrix, sort rows by maximum element. Input : test_list = [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]] Output : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]] Explanation : 18, 10, 8 and 5 are maximum elements in rows, hence sorted. Input : test_list = [[9, 10, 3], [10, 18, 3], [0, 3, 5]
4 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 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
5 min read
Python program to sort a list of tuples alphabetically
Given a list of tuples, write a Python program to sort the tuples alphabetically by the first item of each tuple. Examples: Input: [("Amana", 28), ("Zenat", 30), ("Abhishek", 29), ("Nikhil", 21), ("B", "C")] Output: [('Amana', 28), ('Abhishek', 29), ('B', 'C'), ('Nikhil', 21), ('Zenat', 30)] Input:
3 min read
Python - Filter Tuples by Kth element from List
Given a list of tuples, filter by Kth element presence in List. Input : test_list = [("GFg", 5, 9), ("is", 4, 3), ("best", 10, 29)], check_list = [4, 2, 3, 10], K = 2 Output : [('is', 4, 3)] Explanation : 3 is 2nd element and present in list, hence filtered tuple. Input : test_list = [("GFg", 5, 9),
5 min read
Python - Sort by Maximum digit in Element
Given a List of Elements, sort by the maximum digit of the element present in the List. Input : test_list = [234, 92, 8, 721] Output : [234, 721, 8, 92] Explanation : 4 < 7 < 8 < 9, sorted by maximum digits. Input : test_list = [92, 8, 721] Output : [721, 8, 92] Explanation : 7 < 8 <
6 min read
Python program to find the key of maximum value tuples in a dictionary
Given a dictionary with values as tuples, the task is to write a python program to find the key of maximum value tuples. Examples: Input : test_dict = {'gfg' : ("a", 3), 'is' : ("c", 9), 'best' : ("k", 10), 'for' : ("p", 11), 'geeks' : ('m', 2)}Output : forExplanation : 11 is maximum value of tuple
6 min read
Python - Row with Maximum Record Element
Sometimes, while working with Python Records, we can have a problem in which we need to find the row with maximum record element. This kind of problem can come in domains of web development and day-day programming. Let's discuss certain ways in which this task can be performed. Input : test_list = [
7 min read
Python - Maximum of Similar Keys in Tuples
Sometimes, while working with Python tuples, we can have a problem in which we need to perform maximum of all values of the equal keys in Tuple list. This kind of application in useful in many domains such as web development and day-day programming. Let's discuss certain ways in which this task can
4 min read
Python Program to Sort the list according to the column using lambda
We often need to organize data based on a particular value, such as sorting rows in a dataset by a column. Python makes this task simple by using the sorted() function along with a lambda function. In this article, we will explore various approaches to Sorting the list according to column.Let's unde
3 min read