Home » Python Program to Sort list of tuple by Nth element of tuple

# Python Program to Sort list of tuple by Nth element of tuple

In this article lets write a Python Program to Sort list of tuple by Nth element of tuple. When working with Python lists, we may run across an issue where we need to sort the list based on any tuple element. These must be a generic technique to sort by a certain tuple index. Let’s go over several different approaches to solve this program.

Contents

## Python Program to Sort list of tuple by Nth element of tuple using sort() with lambda Function

Both sort() and lambda function combined is used to solve the problem. The lambda function is used inside the sort() Method with the appropriate tuple element index to sort the tuple list accordingly.

Code :

``````sample_list = [(2,6,4), (7,4,9), (5,1,6), (8,5,0)]
print("The Given list : ", sample_list)

#index
n = 1

# sort() + lambda
sample_list.sort(key = lambda a: a[n])

print("List  after sorting : ", sample_list)``````

Output :

The Given list : [(2, 6, 4), (7, 4, 9), (5, 1, 6), (8, 5, 0)]
List after sorting : [(5, 1, 6), (7, 4, 9), (8, 5, 0), (2, 6, 4)]

## Sorting the list of tuples using itemgetter() Method

The itemgetter() Method is used inside the sort() method to select the appropriate index of the tuple element and sort accordingly.

Code :

``````from operator import itemgetter

sample_list = [(2,6,4), (7,4,9), (5,1,6), (8,5,0)]
print("The Given list : ", sample_list)

#index
n = 1

# sort() + lambda
sample_list.sort(key = itemgetter(n))

print("List  after sorting : ", sample_list)``````

Output :

The Given list : [(2, 6, 4), (7, 4, 9), (5, 1, 6), (8, 5, 0)]
List after sorting : [(5, 1, 6), (7, 4, 9), (8, 5, 0), (2, 6, 4)]

Similar Posts: