Write a Python program to Closest Pair to Kth index element in Tuple


The program is written in Python and performs the following operations:

  • Defines a list of tuples called "val".
  • Prints the list of tuples.
  • Defines a tuple called "t" with the value (20, 2).
  • Defines a variable "K" with the value 1.
  • Uses the "min" function to find the index of the tuple in the "val" list that is closest to the tuple "t", with respect to the value at the K-th index.
  • The "min" function uses the "lambda" function to calculate the absolute difference between the K-th index of each tuple in the "val" list and the K-th index of the tuple "t".
  • Prints the nearest tuple from the "val" list.

The final output of the program will be the nearest tuple from the list "val" with respect to the first index (K = 1) of the tuple "t".

Source Code

val = [(23, 18), (9, 2), (2, 3), (9, 18), (23, 2)]
print("List : " ,val)
t = (20, 2)
K = 1
res = min(range(len(val)), key = lambda sub: abs(val[sub][K - 1] - t[K - 1]))
print("Nearest Tuple : " ,val[res])

Output

List :  [(23, 18), (9, 2), (2, 3), (9, 18), (23, 2)]
Nearest Tuple :  (23, 18)

Example Programs