Minimum of pairs between two lists, is there a quicker way?

Viewed 112

I have two (very long) lists. I want to find the sum of the minimum of each pair in the list. Eg, if

X = [2,3,4]
Y = [5,4,2]

then, the sum would be 2+3+2 = 7. At the moment, I'm doing this by zipping the lists and using a list comprehension. My lists are X and Y:

mins = [min(x,y) for x,y in zip(X,Y)]
summed_mins = sum(mins)

This is causing serious runtime issues in my program. Is there a faster way to do this? List comprehensions are the fastest that I know of.

1 Answers

You can use Python generators and the built-in map function to avoid the creation of the list, but this will probably be just slightly faster (thanks to Veedrac):

summed_mins = sum(map(min, x, y))

Alternatively, you can use Numpy. Here is how:

summed_mins = np.stack((X, Y)).min(axis=0).sum()

If you can store the input list directly as Numpy arrays, this can be much faster. If you can even store it directly in a 2D Numpy array, you don't need the np.stack call resulting in a much faster code. If you cannot store/create the input directly as Numpy arrays, you can create the Numpy arrays on the fly quickly by specifying the data type (assuming you are sure the list contain small integers). Here is an example:

summed_mins = np.stack((np.array(a, np.int64), np.array(b, np.int64))).min(axis=0)
Related