# For each element in a list, finding the element in a second list, that minimizes a distance function

Getting started:

For a given number x (say -5) I want to know which element of a list y (say [2, -6]), minimizes the value of distance function d (say the absolute value) which applied on x and all elements of y. My current solution to this problem is

x = -5
y = [2, -6]
def d(a1, a2):
return abs(a1-a2) # more complicated in real application

min(y, key = lambda _: d(_, x)) # correctly returns -6


Next level: x is actually a list (say [1, 5, -10]), so I build a list comprehension on top my previous solution:

x = [1, 5, -10]
[min(y, key = lambda _: d(_, xindex)) for xindex in x] # correctly returns [2, 2, -6]


As this type of problem seems quite basic to me, I expect a simple solution for this problem (like argmin(list1=x, list2=y, function=d)). Here is a question where it is shown how a custom distance matrix can be build. But this alone (the step from the distance matrix to the argmins would also have to be done) seems too be more complicated than my code.

Overall my question is: is my code fine, or is there a nicer solution?

• Do you want to know the index of the value or the value itself that minimizes that distance? Jul 1, 2019 at 13:25
• @AlexV I want to know the value itself (eg [2, 2, -6]) that minimizes the distance. Jul 1, 2019 at 13:30

The approach is fine and this is exactly the purpose of the key attribute of min.
I’d just nitpick that the _ variable name is usually meant to indicate unused arguments and thus, using it inside the lambda goes against conventions.
Alternatively, you can make use of functools.partial which may yield better performances on larger lists:
[min(y, key=partial(d, a2=xindex)) for xindex in x]

• Thank your for your insights. Your solution only works if I add functools before partial ([min(y, key=functools.partial(d, a2=xindex)) for xindex in x]). Is this a special issue of my system (I'm using a jupyter notebook) or more general? Jul 1, 2019 at 14:51
• Have you tried from functools import partial?