Python program to sort a list of tuples by second Item

PythonServer Side ProgrammingProgramming

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 −

Example

 Live Demo

def tuple_sort(my_tuple):
   return(sorted(my_tuple, key = lambda x: x[1]))
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))

Output

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)]

Explanation

  • A function named ‘tuple_sort’ is defined, that takes a list of tuple as parameter.
  • It is first iterated over using lambda function, and sorted using the ‘sorted’ function.
  • This is returned as output.
  • A list of tuple is defined and is displayed on the console.
  • The ‘tuple_sort’ method is called by passing this list of tuple as parameter.
  • This value is displayed as output on the console.
raja
Published on 11-Mar-2021 12:36:00
Advertisements