In this python tuple program, we will sort a tuple by its float element.
Steps to solve the program
- Take a list of tuples having float elements in it as input.
- We can see that inside each tuple float element is at index 1 in each tuple.
- Sort the tuple by its float element using sorted().
- Inside sorted pass the lambda function to the key to sort the tuple by float element i.e. sorted(tup,key = lambda x: float(x[1])).
- Print the output.
l = [(3,5.6),(6,2.3),(1,1.8)]
print("Original list of tuples: ",l)
l1 = sorted(tup,key = lambda x: float(x[1]))
print("After sorting: ",l1)
Output :
Original list of tuples: [(3, 5.6), (6, 2.3), (1, 1.8)]
After sorting: [(1, 1.8), (6, 2.3), (3, 5.6)]