# Program to find the closest pair to K-th index element of the given tuple using Python

## Introduction

The task is find the closest pair to the Kth index element of the tuple in the given list.

## Program

### Approach 1

```ip_list = [(1, 2), (8,12), (10, 22), (3, 5), (7, 10)]
# Initializing tuple and K
ip_tuple = (1,6)
K = 2
# Using enumerate() + loop
min_d, output = 999999999, None
for index, ele in enumerate(ip_list):
d = abs(ip_tuple[K - 1] - ele[K - 1])
if d < min_d:
min_d, output = d, index
print("The nearest tuple is : " + str(ip_list[output]))```

Output: ### Approach 2

```ip_list = [(1, 2), (8,12), (10, 22), (3, 5), (7, 10)]
# Initializing tuple and K
ip_tuple = (1,6)
K = 2
# Using min() + lambda
output = min(range(len(ip_list)), key = lambda sub: abs(ip_list[sub][K - 1] - ip_tuple[K - 1]))
print("The nearest tuple is : " + str(ip_list[output]))```

Output: ## Explanation

In approach 1, we have used enumerate() function with abs() function. The enumerate() function keeps the track of index value whereas, the abs() functions updates the minimum difference for each element traversed over the loop. The elements at minimum difference index is printed on the screen.

In approach 2, we have used lambda and min() function. The min() function finds the minimum length difference of the elements and lambda is for iterations of list elements.

This site uses Akismet to reduce spam. Learn how your comment data is processed.