Given a tuple, sort the list of tuples in increasing order by any key in tuple.
Examples:
Input : tuple = [(2, 5), (1, 2), (4, 4), (2, 3)] m = 0 Output : [(1, 2), (2, 3), (2, 5), (4, 4)] Explanation: Sorted using the 0th index key. Input : [(23, 45, 20), (25, 44, 39), (89, 40, 23)] m = 2 Output : Sorted: [(23, 45, 20), (89, 40, 23), (25, 44, 39)] Explanation: Sorted using the 2nd index key
Given tuples, we need to sort them according to any given key. This can be done using 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.
Below is the Python implementation of the above approach:
# Python code to sort a list of tuples # according to given key. # get the last key. def last(n):
return n[m]
# function to sort the tuple def sort(tuples):
# We pass used defined function last
# as a parameter.
return sorted (tuples, key = last)
# driver code a = [( 23 , 45 , 20 ), ( 25 , 44 , 39 ), ( 89 , 40 , 23 )]
m = 2
print ( "Sorted:" ),
print (sort(a))

Output:
Sorted: [(23, 45, 20), (89, 40, 23), (25, 44, 39)]
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a studentfriendly price and become industry ready.
Recommended Posts:
 Python  Remove duplicate tuples from list of tuples
 Python  Find the tuples containing the given element from a list of tuples
 Python  Remove tuples from list of tuples if greater than n
 Python  Remove tuples having duplicate first value from given list of tuples
 Python  Count tuples occurrence in list of tuples
 Python  Combining tuples in list of tuples
 Python  Convert string tuples to list tuples
 Python  How to Concatenate tuples to nested tuples
 Python  Filter all uppercase characters Tuples from given list of tuples
 Python program to find Tuples with positive elements in List of tuples
 Python program to find tuples which have all elements divisible by K from a list of tuples
 Sort all even numbers in ascending order and then sort all odd numbers in descending order
 Python  Tuples with maximum key of similar values
 Python List Comprehension  Sort evenplaced elements in increasing and oddplaced in decreasing order
 Sort evenplaced elements in increasing and oddplaced in decreasing order
 Sort a Matrix in all way increasing order
 Sort only nonprime numbers of an array in increasing order
 Sort even and odd placed elements in increasing order
 Sort elements of an array in increasing order of absolute difference of adjacent elements
 Minimize Cost to sort a String in Increasing Order of Frequencies of Characters
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.