+3 votes
in Programming Languages by (17.2k points)
I have two lists of the same length. I want to find the element-wise maximum and minimum from those two lists. Is there a Pythonic way for it?

E.g.

For the following two lists

a=[14, 34, 77, 123, 5, 19, 33, 6]

b=[54, 12, 76, 23, 45, 9, 23, 1]

The result should be

min_a_b = [14, 12, 76, 23,  5,  9, 23,  1]

max_a_b = [ 54,  34,  77, 123,  45,  19,  33,   6]

1 Answer

0 votes
by (30.3k points)
edited by

Numpy's functions maximum() and minimum() can be used to get element-wise maximum and minimum of two arrays respectively.

You can use the following code.

>>> import numpy as np
>>> a=[14, 34, 77, 123, 5, 19, 33, 6]
>>> b=[54, 12, 76, 23, 45, 9, 23, 1]
>>> min_a_b = np.minimum(a,b)
>>> min_a_b
array([14, 12, 76, 23,  5,  9, 23,  1])
>>> max_a_b = np.maximum(a,b)
>>> max_a_b
array([ 54,  34,  77, 123,  45,  19,  33,   6])

You can also use fmax() and fmin() functions.

>>> import numpy as np
>>> a=[14, 34, 77, 123, 5, 19, 33, 6]
>>> b=[54, 12, 76, 23, 45, 9, 23, 1]
>>> max_a_b = np.fmax(a,b)
>>> max_a_b
array([ 54,  34,  77, 123,  45,  19,  33,   6])
>>> min_a_b = np.fmin(a,b)
>>> min_a_b
array([14, 12, 76, 23,  5,  9, 23,  1])

...