Sort a tuple of tuples by 2nd item


The program is written in Python and it sorts a tuple of tuples based on the value of the second element in each tuple. Initially, a tuple t is created containing 5 tuples, each containing a character and a number. The program then sorts the tuple t using the sorted() function and the key argument to specify a lambda function for sorting. The lambda function takes each tuple x in the list and returns its second element x[1]. This means that the tuples will be sorted based on their second elements, in ascending order. Finally, the program converts the sorted list back to a tuple and prints the result.

Source Code

t = (('a', 53), ('b', 37), ('c', 23), ('d', 1), ('e', 18))
t = tuple(sorted(list(t), key=lambda x: x[1]))
print(t)
 

Output

(('d', 1), ('e', 18), ('c', 23), ('b', 37), ('a', 53))

Example Programs