How to find minimum and maximum value in a heterogeneous list in Python?


0

In this tutorial we will learn how to find the minimum or maximum value in a heterogeneous list using python.

A heterogeneous list is one that has heterogeneous items(items with an arbitrary data type). Let us assume: x = [‘xyz’, 5, ‘test’, 6, 3]. The list ‘a’ have items of two different types of record, int, and string.

For that a string if you want to find the minimum and maximum value we can’t do it directly. Rather, you need to filter the integer(int) values from the list and then implement the min()/max() function.

This can be done anyhow using list understanding or using a lambda function as given.

x = ['xyz, 5, 6, 'sample']
#list comprehension
mini = min(i for i in x if isinstance(i, int))
print("Minimum value is", mini)
#using lambda function
maxi = max(x, key = lambda i: (isinstance(i, int), i)
print("Maximum value is", maxi)

Output:

Minimum value is 5
Maximum value is 6

In the upper code, you have a list with only two (2) int values, 5 and 6. We will filter these values by using the upper function followed by a min()/max() function.

Nested lists: minimum and maximum value in a heterogeneous list in python


Consider a nested list, x = [[‘sample’, 1], [‘xyz’, 7], [‘bit’, 5]]. This list has three (3) items and each item is furthermore a list. If you use the min()/max() function for this list to find the min and maxi values in the list you will not get the expected result. For example:

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

Output:

Minimum value is ['xyz', 7]

The anticipated output is [‘code’, 1] but you get will get a different output. This will come because the series objects are classified with other objects of the same series type by following the lexicographical order. Under this in the beginning, the first two items are similar, followed by the other items.
Thus, in the upper code when you pass the list ‘x’ to the min() function, it compares the first item in each item inner the nested list.

To get the intended output, you use the lambda function as given,

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

Output:

Minimum value is ['sample', 1]

This code will works the same for the max() function also.

Also read: How to Merge PDF File in Python?


Like it? Share with your friends!

0
Developer

0 Comments