When it is required to sort a list of tuples based on the second item, the lambda function and ‘sorted’ method can be used.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on). A list of tuple basically contains tuples enclosed in a list.
Anonymous function is a function which is defined without a name.
In general, functions in Python are defined using ‘def’ keyword, but anonymous function is defined with the help of ‘lambda’ keyword. It takes a single expression, but can take any number of arguments. It uses the expression and returns the result of it.
The ‘sorted’ method is used to sort the elements of a list.
Below is a demonstration for the same −
def tuple_sort(my_tuple): return(sorted(my_tuple, key = lambda x: x)) my_tuple = [('bill', 11), ('rick', 45), ('john', 89), ('liv', 25)] print("The list of tuple is : ") print(my_tuple) print("After sorting, the list of tuple becomes : ") print(tuple_sort(my_tuple))
The list of tuple is : [('bill', 11), ('rick', 45), ('john', 89), ('liv', 25)] After sorting, the list of tuple becomes : [('bill', 11), ('liv', 25), ('rick', 45), ('john', 89)]