Sort list of tuples by specific ordering in Python

PythonServer Side ProgrammingProgramming

When it is required to sort the list of tuples in a specific order, the 'sorted' method can be used.

The 'sorted' method is used to sort the elements of a list.

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 for the same −

Example

Live Demo

def tuple_sort(my_tup):
   return(sorted(my_tup, key = lambda x: x[1]))

my_tuple = [('Mahe', 11), ('Aisha', 33), ('Will', 50), ('Root', 65)]

print("The list of tuple is : ")
print(my_tuple)
print("The tuple after placing in a specific order is : ")
print(tuple_sort(my_tuple))

Output

The list of tuple is :
[('Mahe', 11), ('Aisha', 33), ('Will', 50), ('Root', 65)]
The tuple after placing in a specific order is :
[('Mahe', 11), ('Aisha', 33), ('Will', 50), ('Root', 65)]

Explanation

  • A method named 'tuple_sort' is defined that takes a list of tuple as parameter.
  • It uses the 'sorted' method to sort the list of tuple in the order based on the first element in every tuple inside the list of tuple.
  • A list of tuple is defined, and is displayed on the console.
  • The function is called by passing this list of tuple as parameter.
  • This operation's data is stored in a variable.
  • This variable is the output that is displayed on the console.
raja
Published on 13-Mar-2021 05:45:45
Advertisements