# Closest Pair to Kth index element in Tuple using Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

When it is required to find the closest pair to the Kth index element in a tuple, the ‘enumerate’ method can be used along with ‘abs’ method.

Below is the demonstration of the same −

## Example

Live Demo

my_list = [(5, 6), (66, 76), (21, 35), (90, 8), (9, 0)]

print("The list is : ")
print(my_list)

my_tuple = (17, 23)
print("The tuple is ")
print(my_tuple)
K = 2
print("The value of K has been initialized to ")
print(K)

min_diff, my_result = 999999999, None
for idx, val in enumerate(my_list):
diff = abs(my_tuple[K - 1] - val[K - 1])
if diff < min_diff:
min_diff, my_result = diff, idx

print("The tuple nearest to Kth index element is : " )
print(my_list[my_result])

## Output

The list is :
[(5, 6), (66, 76), (21, 35), (90, 8), (9, 0)]
The tuple is
(17, 23)
The value of K has been initialized to
2
The tuple nearest to Kth index element is :
(21, 35)

## Explanation

• A list of tuple is defined, and is displayed on the console.

• A tuple is defined, and is displayed on the console.

• The value of K is defined.

• The list is iterated over, and the absolute difference is assigned a value.

• If this difference is less than a specific value, they are assigned to different variables.

• This is displayed as output on the console.

Updated on 17-Apr-2021 12:56:44