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.
Here's an example of sorting a list of tuples by the second element of each tuple:
my_list = [(1, 3), (4, 2), (3, 1)]
sorted_list = sorted(my_list, key=lambda x: x[1])
print(sorted_list) # [(3, 1), (4, 2), (1, 3)]
You can also use the itemgetter()
function from the operator
module as the key for sorting, it will be more efficient than lambda function
from operator import itemgetter
my_list = [(1, 3), (4, 2), (3, 1)]
sorted_list = sorted(my_list, key=itemgetter(1))
print(sorted_list) # [(3, 1), (4, 2), (1, 3)]
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.