Python Program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple

This is a Python Program to sort a list of tuples in increasing order by the last element in each tuple.

Problem Description

The program takes a list of tuples and sorts the list of tuples in increasing order by the last element in each tuple.

Problem Solution

1. Take a list of tuples from the user.
2. Define a function which returns the last element of each tuple in the list of tuples.
3. Define another function with the previous function as the key and sort the list.
4. Print the sorted list.
5. Exit.

Program/Source Code

Here is source code of the Python Program to sort a list of tuples in increasing order by the last element in each tuple. The program output is also shown below.

def last(n):
    return n[-1]  
 
def sort(tuples):
    return sorted(tuples, key=last)
 
a=input("Enter a list of tuples:")
print("Sorted:")
print(sort(a))
Program Explanation

1. User must enter a list of tuples.
2. The function last returns the last element of each tuple in the list of tuples.
3. The function sort returns the sorted list with the last function as its key.
4. The sorted list is then printed.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Enter a list of tuples:[(2,5),(1,2),(4,4),(2,3)]
Sorted:
[(1, 2), (2, 3), (4, 4), (2, 5)]
 
Case 2:
Enter a list of tuples:[(23,45),(25,44),(89,40)]
Sorted:
[(89, 40), (25, 44), (23, 45)]

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.