Given a tuple, our task is to sort the list of tuples in increasing order by any key in a tuple. We need to sort them according to any given key.to do this here we use sorted() function where we sort them using key=last and store last as the key index according to which we have to sort the given tuples.
Example
Input: A = [(2, 55), (1, 20), (4, 40), (2, 30)]
k = 0
Output: [(1, 20), (2, 30), (2, 55), (4, 40)]
Explanation
Increasing Sorted order using the 0th index key.
Algorithm
Step 1: get the last key value. Step 2: next we use inbuilt function sorted () method where we sort them using key=last and store last as the key index according to which we have to sort the given tuples. Step 3: display sorted list.
Example Code
# Python program to sort a list of tuples
# in increasing order by any key
# get the last key.
def data(n):
return n[k]
# function to sort the tuple
def tuplesort(tup):
# We pass used defined function last
# As a parameter.
return sorted(tup, key = data)
# Driver code
a = [(230, 456, 120), (205, 414, 39), (89, 410, 213)]
k = int(input("Enter the Index ::>"))
print("Sorted:"),
print(tuplesort(a))
Output
Enter the Index ::>2 Sorted: [(205, 414, 39), (230, 456, 120), (89, 410, 213)]