Example:
tuple = ("python", "includehelp", 43, 54.23)
Sorting a list of tuples by second item
In this program, we have a list of tuples and we need to sort the list of tuples by the index of sorting which will be the second item of the tuple.
We basically will use a sorting algorithm but instead of using the Ist value of the list, we will use the second element of the tuple.
Example:
Input:
[(2, 5), (9, 1), (4, 6), (2, 8), (1, 7)]
Output:
[(9, 1), (2, 5), (4, 6), (1, 7), (2, 8)]
In Python programming language, there are multiple ways to perform a single task in different ways and it totally depends on the programmer and then the need of the software being developed that which one should be used.
Method 1:
Using binary sorting technique for sorting. We will access the second element of the tuple as an index for sorting the list.
Program:
Output:
Method 2 : Using sorting methods
Python provides us with some built-in sorting methods. While using the sorting methods, we need to pass a method to the method which will swap the element to the second element of tuple.
Using sort() method
Output:
Using sorted() method
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer