This is a Python Program to sort a list of tuples in increasing order by the last element in each tuple.
The program takes a list of tuples and sorts the list of tuples in increasing order by the last element in each tuple.
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.
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))
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.
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.
- Apply for Python Internship
- Practice Programming MCQs
- Check Python Books
- Check Information Technology Books
- Apply for Programming Internship