W3docs

How to sort a list/tuple of lists/tuples by the element at a given index?

You can use the sorted() function with the key parameter to specify a function that extracts the element at the desired index.

You can use the sorted() function with the key parameter to specify a function that extracts the element at the desired index.

Here's an example of sorting a list of tuples by the second element of each tuple:

an example of sorting a list of tuples by the second element of each tuple

python— editable, runs on the server

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

You can also use the itemgetter() function from the operator module as the key for sorting, it will be more efficient than lambda function

an example of sorting a list of tuples by the second element of each tuple by using the itemgetter function

python— editable, runs on the server

Note that the above examples will sort the list in ascending order. To sort in descending order, pass reverse=True as a parameter to the sorted() function.