Example:
tuple = ("python", "includehelp", 43, 54.23)
List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of ordered set of values enclosed in square brackets [].
Example:
list = [3 ,1, 5, 7]
A list of tuples is a list whose each element is a tuple.
Example:
upList = [("python", 7), ("learn" , 1), ("programming", 7), ("code" , 3)]
Sorting a list of tuples in increasing order by the last element in each tuple
We need to sort the List of Tuples in Increasing Order By the last Element in Each Tuple. For this, we will be simply sorting the List but the value to be used while comparison will be the second value of the list.
We can write our sorting code or we can use built-in python methods to perform the task.
Method 1: Writing sorting code
We can use any sorting technique and use the sorting value to be the second element of the tuple. Here, we will use bubble sort with tup[2] as the comparison value.
Program:
Output:
Method 2:
We can also perform the task of sorting by the last element using built-in methods provided in the python library.
There are two such methods to perform the task. They are,
(i) Sorted() method
The sorted method in the python library is used to return a sorted list. We will pass parameters to use the last value of tuple to sort the list based on the last value of the tuple.
Program:
Output:
(ii) sort() method
The sort() method also sorts the given list and takes a lambda function for defining the key and order of sorting.
Program:
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer