Find Min-Max in heterogeneous list in Python


A python list can contain both strings and numbers. We call it a heterogeneous list. In this article we will take such a list and find the minimum and maximum number present in the list.

Finding Minimum

In this approach we will take the isinstance function to find only the integers present in the list and then apply the min function to get the minimum value out of it.

Example

 Live Demo

listA = [12, 'Sun',39, 5,'Wed', 'Thus']

# Given list
print("The Given list : ",listA)

res = min(i for i in listA if isinstance(i, int))

# Result
print("The minimum value in list is : ",res)

Output

Running the above code gives us the following result −

The Given list : [12, 'Sun', 39, 5, 'Wed', 'Thus']
The minimum value in list is : 5

Finding Maximum value

We take a similar approach as above. But this time we can also use the lambda function along with the max function to get the maximum value.

Example

 Live Demo

listA = [12, 'Sun',39, 5,'Wed', 'Thus']

# Given list
print("The Given list : ",listA)

# use max
res = max(listA, key=lambda i: (isinstance(i, int), i))

# Result
print("The maximum value in list is : ",res)

Output

Running the above code gives us the following result −

The Given list : [12, 'Sun', 39, 5, 'Wed', 'Thus']
The maximum value in list is : 39

Updated on: 26-Aug-2020

390 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements