How to Sort Tuples in a Special Order in Python


In this example we will show the methods to sort a list of Tuples in increasing order of the last element in each Tuple in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

def last(n):
    return n[-1]

a = [(3,15),(2,6),(8,5),(9,8),(4,9),(7,6),(14,2)]
a.sort(key=last)
print("The sorted result: ")
print(a)

Output:

The sorted result: 
[(14, 2), (8, 5), (2, 6), (7, 6), (9, 8), (4, 9), (3, 15)]
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments