Find min and max value in a heterogeneous list in Python

Today we will discuss how to find the minimum or maximum value in a heterogeneous list.

A heterogeneous list is one that contains heterogeneous items( items with arbitrary data type). Example: a = [‘abc’, 5, ‘good’, 6, 3]. The list ‘a’ contains items of two different types of data, int, and string.

For such a string if we want to find the minimum and maximum value we can not do it directly. Instead, we first need to filter the integer values from the list and then apply the min()/max() function.

This can be done either by using list comprehension or using a lambda function as shown.

a = ['abc', 5, 6, 'code']
#list comprehension

mini = min(i for i in a if isinstance(i, int))
print("Minimum value is", mini)

#using lambda function
maxi = max(a, key = lambda i: (isinstance(i, int), i)
print("Maximum value is", maxi)

Output:

Minimum value is 5
Maximum value is 6

In the above code, we have a list with only two integer values, 5 and 6. We filter out these values by using the above methods followed by a min()/max() function.

Nested lists: min and max value in a heterogeneous list

Consider a nested list, a = [[‘code’, 1], [‘abc’, 7], [‘bit’, 5]]. This list has three items and each item is again a list. If we use the min()/max() function for this list to find the minimum and maximum values in the list we will not get the desired result. For example:

a = [['code', 1], ['abc', 7], ['bit', 5]]
print("Minimum value is ", min(a))

Output:

Minimum value is ['abc', 7]

The expected output is [‘code’, 1] but we get a different output. This happens because the sequence objects are classified with other objects of the same sequence type by following the lexicographical ordering. Under this initially, the first two items are compared, followed by the other items.
Hence in the above code when we pass the list ‘a’ to the min() function, it compares the first item in each item inside the nested list.

To get the desired output, we use the lambda function as shown,

mini = min(a, key=lambda x = x[1])
print("Minimum value is ", mini)

Output:

Minimum value is ['code', 1]

This works the same for the max() function.

Also read: Find most frequent element in a Python List

Leave a Reply

Your email address will not be published. Required fields are marked *