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.
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.
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)
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
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.
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)
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