sort list of tuples in python

How to Sort List of Tuples by Second Element in Python

Python allows you to store data as list of lists or list of tuples making it easy to store and process information. Sometimes you may need to sort list of tuples by second element in python. In this article, we will learn how to sort list of tuples by nth element in python.


How to Sort List of Tuples by Second Element in Python

Let us say you have the following information present as list of lists or list of tuples.

data = [[1,2,3], [4,5,6], [7,8,9]]
OR
data = [(1,2,3), (4,5,6), (7,8,9)]

Let us say you want to sort by the second element in each list item. In other words, you want to sort 2, 5, 8, where 2 is the second element of 1st item, 5 is the 2nd element of 2nd item and 8 is the 2nd element of 3rd item.

There are several ways to do this in python.

1. Using sorted function

In this approach, we will use sorted() function to sort our list and return the sorted list separately.

sorted_by_second = sorted(data, key=lambda item: item[1])

In the above function, we specify the key argument of sorted function to be 2nd item, with the help of lambda function.

If you want to sort by nth element, you can modify the above command as shown by replacing 1 with n-1.

sorted_by_second = sorted(data, key=lambda item: item[n-1])

The above commands sort the list in ascending order of items. If you want to sort them in descending order of items, add reverse=True argument in the above command.

sorted_by_second = sorted(data, key=lambda item: item[n-1], reverse = True)

2. Using sort function

The above mentioned sorted() function generates and returns a new list without modifying the original list. If you want to sort them items in place, that is, modify the existing list to sorted items, you can use sort() function as shown below. Here is the command to sort list of lists or tuples by second element in each item.

data.sort(key=lambda item: item[1])

If you want to sort the list based on nth element in each item, replace 1 with n-1 above.

data.sort(key=lambda item: item[n-1])

The above command sorts the items in ascending order. If you want to sort by descending order, add reverse = True argument to above function.

data.sort(key=lambda item: item[n-1], reverse = True)

In this article, we have learnt how to sort list of lists or tuples by nth element. Depending on whether you want to sort the list in place or not, you can use sort() or sorted() function as per your requirement.

Also read:

How to Get Key With Max Value in Dictionary
How to Configure Python Flask to Be Externally Visible
How to Get Difference Between Two Lists in Python
How to Import Other Python File
How to Remove Punctuation from String in Python

Leave a Reply

Your email address will not be published. Required fields are marked *