Python program to sort a tuple by its float element

PythonServer Side ProgrammingProgramming

In this problem, our task to sort a tuple (consisting of float elements) using its float elements. Here we use built-in method sorted () and how can this be done using in place method of sorting.


tuple = [('AAA', '10.265'), ('BBB', '24.107'), ('CCC', '26.541'), ('DDD', '14.256'), ('EEE', '11.365')]
[('CCC', '26.541'), ('BBB', '24.107'), ('DDD', '14.256'), ('EEE', '11.365'), ('AAA', '10.265')]


Step 1: Given a list.
Step 2: To sort using sorted ().
Step 3: Sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted.
Step 4: Key(optional) is a function that would serve as a key or a basis of sort comparison.
Step 5: If Reverse (optional) is true, then the iterable would be sorted in reverse (descending) order, by default it is set as false.

Example Code

# Python code to sort a tuples by its float element
def tuplesort(A):
   return(sorted(A, key = lambda x: float(x[1]), reverse = True))
   # Driver Code
   A = [('Adwaita', '19.215'), ('Aadrika', '10.117'), ('Babai', '14.589'), ('Mona', '14.216'), ('Sanj', '8.365')]
print("Sort of Tuples By Its Float Number ::",tuplesort(A))


Sort of Tuples By Its Float Number :: [('Adwaita', '19.215'), ('Babai', '14.589'), ('Mona', '14.216'), ('Aadrika', '10.117'), ('Sanj', '8.365')]
Published on 26-Sep-2018 11:59:33