Q:

Python program to sort tuples by their maximum element

belongs to collection: Python Tuple Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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)]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to find tuples with positive elemen... >>
<< Python program to convert tuple into list by addin...