Home »
Python »
Python programs
Python program to sort tuples by their maximum element
Here, we have a list of tuples and we need to sort all the tuples of the list using the maximum element of the tuple.
Submitted by Shivang Yadav, on September 02, 2021
Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.
Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.
Example:
tuple = ("python", "includehelp", 43, 54.23)
List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of an ordered set of values enclosed in square brackets [].
Example:
list = [3 ,1, 5, 7]
Sorting Tuples by Their Maximum Element
We have a list of tuples and we need to sort all tuples of the list using the maximum element of the list.
Input:
[(32, 5, 7), (12, 6, 3), (16, 9), (1, 2, 3, 8)]
Output:
[(32, 5, 7), (16, 9), (12, 6, 3), (1, 2, 3, 8)]
We will find the maximum element from the tuples, then sort the tuples of the list using the maximum element. And for performing the task we have multiple methods. Let's see them,
Method 1:
One method to solve the problem is by traversing the list and then for each tuple find the maximum value using max(). Then sort the values using the max value.
# Python Program to sort Tuples
# by Their Maximum Element
def getMaxValTup(tup):
return max(tup)
# Creating and print tuple list
tupList = [(32, 5, 7), (12, 6, 3), (16, 9), (1, 2, 3, 8)]
print("Unordered list of tuples : " + str(tupList))
# Sorting the List using sort function
tupList.sort(key = getMaxValTup, reverse = True)
# printing Sorted List of Tuple
print("Ordered list of tuples : " + str(tupList))
Output:
Unordered list of tuples : [(32, 5, 7), (12, 6, 3), (16, 9), (1, 2, 3, 8)]
Ordered list of tuples : [(32, 5, 7), (16, 9), (12, 6, 3), (1, 2, 3, 8)]
Method 2:
A similar way to solve the task is using the lambda function to find the maximum value instead of using an extra method. Then sort it.
# Python Program to sort Tuples
# by Their Maximum Element
def getMaxValTup(tup):
return max(tup)
# Creating and print tuple list
tupList = [(32, 5, 7), (12, 6, 3), (16, 9), (1, 2, 3, 8)]
print("Unordered list of tuples : " + str(tupList))
# Sorting the List using sort function
tupList.sort(key = lambda tup : max(tup), reverse = True)
# printing Sorted List of Tuple
print("Ordered list of tuples : " + str(tupList))
Output:
Unordered list of tuples : [(32, 5, 7), (12, 6, 3), (16, 9), (1, 2, 3, 8)]
Ordered list of tuples : [(32, 5, 7), (16, 9), (12, 6, 3), (1, 2, 3, 8)]
Python Tuple Programs »