Python: Find the maximum values in a given heterogeneous list using lambda
29. Heterogeneous Max Finder Lambda
Write a Python program to find the maximum value in a given heterogeneous list using lambda.
Sample Solution:
Python Code :
# Define a function 'max_val' that takes a list 'list_val' as input
def max_val(list_val):
# Find the maximum value in 'list_val' based on two criteria:
# 1. First, sort by whether the element is an integer or not (True for integers, False for non-integers)
# 2. Second, sort lexicographically by the elements themselves
max_val = max(list_val, key=lambda i: (isinstance(i, int), i))
# Return the maximum value found in the list
return max_val
# Create a list 'list_val' containing a mix of strings and integers
list_val = ['Python', 3, 2, 4, 5, 'version']
# Print the original list 'list_val'
print("Original list:")
print(list_val)
# Find and print the maximum values in the list using the 'max_val' function and lambda expressions
print("\nMaximum values in the said list using lambda:")
print(max_val(list_val))
Sample Output:
Original list: ['Python', 3, 2, 4, 5, 'version'] Maximum values in the said list using lambda: 5
For more Practice: Solve these Related Problems:
- Write a Python program to find the minimum value in a heterogeneous list using lambda, ignoring non-comparable types.
- Write a Python program to determine the maximum string (lexicographically) in a heterogeneous list using lambda.
- Write a Python program to find the longest element in a heterogeneous list based on length (for strings) or value (for numbers) using lambda.
- Write a Python program to extract numeric values from a heterogeneous list and calculate their average using lambda.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to sort a given list of lists by length and value using lambda.
Next: Write a Python program to sort a given matrix in ascending order according to the sum of its rows using lambda.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.