Python | Sorting tuples in ascending order by any key

Python Methods and Functions

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 the given tuples, we need to sort them by any given key. This can be done with the sorted () function, where we sort them using key = last, and store last as the key index according to which we must sort the specified tuples.

Below is the implementation of the above approach in Python:

# Python code to sort the list of tuples
# according to the given key.

 
# get the last key.

def last (n):

return n [m] 

 
# function to sort the tuple

def   sort (tuples):

 

# Pass the defined function to use 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)] 




Tutorials