Different Ways to Sort the List of Tuples

sorted(), list.sort(),itemgetter()

Indhumathy Chelliah
4 min readDec 9, 2022

--

Photo by Sebastiaan Stam: https://www.pexels.com/photo/landscape-sky-hands-woman-11325889/

In this article, let’s learn how to sort the list of tuples using different methods.

Using sorted function

  1. Sorting the list of tuples by the second element in ascending order using sorted()
  2. Sorting the list of tuples by the second element in descending order using sorted()
  3. Sorting the list of tuples by the second element in ascending order using itemgetter
  4. Sorting the list of tuples by the second element in descending order using itemgetter
  5. Multi-level sorting using itemgetter

Using list.sort()

  1. Sorting the list of tuples by the second element in ascending order using list.sort()
  2. 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)…

--

--