w3resource

Python: Find all index positions of the maximum and minimum values in a given list using lambda

Python Lambda: Exercise-46 with Solution

Write a Python program to find the index position and value of the maximum and minimum values in a given list of numbers using lambda.

Sample Solution:

Python Code :

# Define a function 'position_max_min' that finds the positions of the maximum and minimum values in a list
def position_max_min(nums):
    # Find the maximum value and its index in 'nums' using 'max' function with 'enumerate'
    # The 'key' argument specifies a lambda function to evaluate each element by its value
    max_result = max(enumerate(nums), key=(lambda x: x[1]))
    
    # Find the minimum value and its index in 'nums' using 'min' function with 'enumerate'
    # The 'key' argument specifies a lambda function to evaluate each element by its value
    min_result = min(enumerate(nums), key=(lambda x: x[1]))
    
    # Return a tuple containing the index position and value of the maximum and minimum values
    return max_result, min_result

# Create a list 'nums' containing numerical values including integers and floats
nums = [12, 33, 23, 10.11, 67, 89, 45, 66.7, 23, 12, 11, 10.25, 54]

# Print the original list 'nums'
print("Original list:")
print(nums)

# Find the index position and value of the maximum and minimum values using 'position_max_min' function
result = position_max_min(nums)

# Print the index position and value of the maximum and minimum values in the list 'nums'
print("\nIndex position and value of the maximum value of the said list:")
print(result[0])

print("\nIndex position and value of the minimum value of the said list:")
print(result[1]) 

Sample Output:

Original list:
[12, 33, 23, 10.11, 67, 89, 45, 66.7, 23, 12, 11, 10.25, 54]

Index position and value of the maximum value of the said list:
(5, 89)

Index position and value of the minimum value of the said list:
(3, 10.11)

Python Code Editor:

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

Previous: Write a Python program to convert string element to integer inside a given tuple using lambda.

Next: Write a Python program to sort a given mixed list of integers and strings using lambda. Numbers must be sorted before strings.

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.