Custom sorting in list of tuples in Python

PythonServer Side ProgrammingProgramming

When it is required to sort the list of tuples in a customized manner, the 'sort' method can be used.

The 'sort' method sorts the elements of the iterable in a specific order, i.e ascending or descending. It sorts the iterable in-place.

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.

Below is a demonstration of the same −

Example

Live Demo

def tuple_sort(my_tup):
   my_tup.sort(key = lambda x: x[1])
   return my_tup

my_tuple = [('Will', 100), ('John', 67), ('Harold', 86), ('Jane', 35)]

print("The tuple is ")
print(my_tuple)
print("The sorted list of tuple is :")
print(tuple_sort(my_tuple))

Output

The tuple is
[('Will', 100), ('John', 67), ('Harold', 86), ('Jane', 35)]
The sorted list of tuple is :
[('Jane', 35), ('John', 67), ('Harold', 86), ('Will', 100)]

Explanation

  • A function named 'tuple_sort' is defined, that takes a list of tuple as argument.
  • This method uses the 'sort' method to sort the elements of the tuple using the lambda function.
  • Lambda function takes a single expression, but can take any number of arguments.
  • It uses the expression and returns the result of it.
  • A list of tuple is defined, and is displayed on the console.
  • The method is called by passing this list of tuple.
  • This is assigned to a value.
  • It is displayed on the console.
raja
Published on 12-Mar-2021 06:05:17
Advertisements