Different Ways to Sort the List of Tuples
sorted(), list.sort(),itemgetter()
4 min readDec 9, 2022
In this article, let’s learn how to sort the list of tuples using different methods.
Using sorted function
- Sorting the list of tuples by the second element in ascending order using sorted()
- Sorting the list of tuples by the second element in descending order using sorted()
- Sorting the list of tuples by the second element in ascending order using itemgetter
- Sorting the list of tuples by the second element in descending order using itemgetter
- Multi-level sorting using itemgetter
Using list.sort()
- Sorting the list of tuples by the second element in ascending order using list.sort()
- Sorting the list of tuples by the second element in descending order using list.sort()
Using sorted function
sorted() — It will return a new sorted list.
Example 1: Sorting the list of tuples by the second element in ascending order using sorted()
lst1=[('blue',25,20),('red',21,35),('yellow',60,27)]
sorted_list=sorted(lst1,key=lambda x:int(x[1]))
print("Original List: ",lst1)…