Write a Python program to sort a tuple by its float element


The program is written in Python and it sorts a list of tuples based on the value of the second element in each tuple, which represents a percentage. Initially, a list Percent is created containing 5 tuples, each with a name and a percentage represented as a string. The program sorts the list Percent using the sorted() function and the key argument to specify a lambda function for sorting. The lambda function takes each tuple a in the list and returns the float representation of its second element a[1]. This means that the tuples will be sorted based on their second elements, which are the percentages, in descending order. The reverse argument is set to True to sort in descending order.

Source Code

Percent = [('Ram', '89.20'), ('Siva', '76.45'), ('Pooja', '84.40'), ('Tara', '68.43'), ('Jeeva', '91.40')]
print( sorted(Percent, key=lambda a: float(a[1]), reverse=True))

Output

[('Jeeva', '91.40'), ('Ram', '89.20'), ('Pooja', '84.40'), ('Siva', '76.45'), ('Tara', '68.43')]

Example Programs