w3resource

Python: Find the maximum and minimum values in a given list of tuples using lambda function

Python Lambda: Exercise-51 with Solution

Write a Python program to find the maximum and minimum values in a given list of tuples using the lambda function.

Sample Solution:

Python Code :

# Define a function 'max_min_list_tuples' that finds the maximum and minimum values in a list of tuples
def max_min_list_tuples(class_students):
    # Find the maximum value in 'class_students' using 'max' function with a lambda key function
    # Extract the second element (index 1) from each tuple and find the maximum value based on that
    return_max = max(class_students, key=lambda item: item[1])[1]
    
    # Find the minimum value in 'class_students' using 'min' function with a lambda key function
    # Extract the second element (index 1) from each tuple and find the minimum value based on that
    return_min = min(class_students, key=lambda item: item[1])[1]
    
    # Return a tuple containing the maximum and minimum values found in the list of tuples
    return return_max, return_min
    
# Create a list of tuples 'class_students' containing class names and corresponding student scores
class_students = [('V', 62), ('VI', 68), ('VII', 72), ('VIII', 70), ('IX', 74), ('X', 65)]

# Print the original list of tuples 'class_students'
print("Original list with tuples:")
print(class_students)

# Find the maximum and minimum values in the list of tuples using the 'max_min_list_tuples' function and print the result
print("\nMaximum and minimum values of the said list of tuples:")
print(max_min_list_tuples(class_students)) 

Sample Output:

Original list with tuples:
[('V', 62), ('VI', 68), ('VII', 72), ('VIII', 70), ('IX', 74), ('X', 65)]

Maximum and minimum values of the said list of tuples:
(74, 62)

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to remove specific words from a given list using lambda.

Next: Write a Python program to remove None value from a given list using lambda function.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.