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:
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++')]
It Python trick can be very useful for solving competitive coding challenges. One such example is, I was asked to write a program for merging overlapping intervals in Biju’s interview. Here, we have to sort the intervals (list of tuples) by their first value.
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.
Great Solution Thanks!
You’re welcome, Roshini!
Hope you find other tutorials useful as well.
tried this with python3?
==> TypeError: ‘<' not supported between instances of 'str' and 'bytes'
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.