Sort Tuple List by First and Second Element in Python

Sorting the list of numbers or characters is easy. We can use sort() method or sorted() built-in function.

In this tutorial, we want to sort a list of tuples by first and second value in the tuple.

Example:

Let’s consider the tuple list having programming languages and its first appearance year.

[(1985, "C++"), (1995, "Java"), (1990, "Python")]

Prerequisite:

Sort Tuple List by First Element in Python

prog_yr_appeared = [(1985, "C++"), (1995, "Java"), (1990, "Python")]

#Ascending Order
print("Ascending Order")
prog_yr_appeared.sort(key= lambda x: x[0])
print(prog_yr_appeared)

#Descending Order
print("Descending Order")
prog_yr_appeared.sort(key= lambda x: x[0], reverse=True)
print(prog_yr_appeared)

Note: We are setting a reverse option as True to sort the list in descending order.

Output:

Ascending Order
[(1985, 'C++'), (1990, 'Python'), (1995, 'Java')]
Descending Order
[(1995, 'Java'), (1990, 'Python'), (1985, 'C++')]

Sort Tuple List by Second Element in Python

With a slight change in lambda function, we can sort the list of tuples by the second value in the tuple.

Here is the Python code.

prog_yr_appeared = [(1985, "C++"), (1995, "Java"), (1990, "Python")]

#Ascending Order
print("Ascending Order")
prog_yr_appeared.sort(key= lambda x: x[1])
print(prog_yr_appeared)

#Descending Order
print("Descending Order")
prog_yr_appeared.sort(key= lambda x: x[1], reverse=True)
print(prog_yr_appeared)

Output:

Ascending Order
[(1985, 'C++'), (1995, 'Java'), (1990, 'Python')]
Descending Order
[(1990, 'Python'), (1995, 'Java'), (1985, 'C++')]

There can be a nested list instead of a list of tuples. In either way, you have to solve this problem using same method. You can read the difference between list and tuple in Python.

This is one of the very tricky questions asked in Python interviews. This method to sort tuple list by first and second element in Python can also help you in solving coding challenge questions.

Comments

  • Roshini P
    August 5, 2020 at 10:45 pm

    Great Solution Thanks!

    • Aniruddha Chaudhari
      August 6, 2020 at 10:36 pm

      You’re welcome, Roshini!

      Hope you find other tutorials useful as well.

  • Mithun
    August 12, 2020 at 2:50 pm

    tried this with python3?
    ==> TypeError: ‘<' not supported between instances of 'str' and 'bytes'

    • Aniruddha Chaudhari
      August 13, 2020 at 9:05 am

      The coding examples demonstrated in this tutorial are tested with Python3. It would be good if you kindly share the code you tried and at what line you are getting this error.

Leave a Reply