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

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

Sorting a list of tuples in increasing order by the last element in each tuple is a common task in programming. Tuples are ordered collections of elements, and sometimes you might want to sort a list of tuples based on a specific element within each tuple.

Problem Statement

You are given a list of tuples, where each tuple contains a sequence of elements. Your task is to implement a function in Python that sorts this list of tuples in increasing order based on the last element of each tuple.

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

def sort_tuples_by_last_element(lst):
    return sorted(lst, key=lambda x: x[-1])

# Example list of tuples
tuple_list = [(1, 4), (3, 2), (8, 9), (5, 7)]

sorted_list = sort_tuples_by_last_element(tuple_list)
print(sorted_list)

How it Works

  1. Defining the Function: We start by defining the sort_tuples_by_last_element(lst) function. This function takes a list of tuples lst as an argument.
  2. Using the sorted() Function: Inside the function, we use the sorted() function to perform the sorting. The sorted() function takes two important parameters:
    • iterable: This is the list of tuples we want to sort.
    • key: This is a function that takes an element from the iterable and returns a value based on which the sorting is done.
  3. Lambda Function for Sorting: In the key parameter of the sorted() function, we use a lambda function to specify that we want to sort based on the last element of each tuple. The lambda function lambda x: x[-1] takes a tuple x and returns its last element, which is used for sorting.
  4. Result: The sorted() function returns a new list containing the sorted tuples. This list is assigned to the sorted_list variable.
  5. Returning the Result: Finally, the sort_tuples_by_last_element() function returns the sorted_list.

Input/ Output

Leave A Reply

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

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...