Sorting Tuples by Second Element and Weights

  • Share this:

Code introduction


This function takes two lists as input, where the first list is a list of tuples and the second list contains corresponding weights. It sorts the tuples based on the second element of each tuple and the corresponding weights.


Technology Stack : list, tuple, lambda expression, sorted function

Code Type : Function

Code Difficulty : Intermediate


                
                    
def aordn(arg1, arg2):
    """
    This function sorts a list of tuples based on the second element in each tuple.
    """
    if not isinstance(arg1, list) or not all(isinstance(item, tuple) and len(item) >= 2 for item in arg1):
        raise ValueError("arg1 must be a list of tuples with at least two elements each")
    
    if not isinstance(arg2, list):
        raise ValueError("arg2 must be a list")
    
    if len(arg1) != len(arg2):
        raise ValueError("Both lists must have the same number of elements")
    
    sorted_list = sorted(arg1, key=lambda x: x[1])
    return sorted_list