Open In App

Python - Closest Pair to Kth index element in Tuple

Last Updated : 12 Nov, 2025
Comments
Improve
Suggest changes
2 Likes
Like
Report

Given a list of tuples and a target tuple, the goal is to find the tuple whose Kth element is closest to the Kth element of the target tuple. Optionally, a threshold K can define the maximum allowable difference. For Example:

Input: t = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)] , tup = (17, 23) and K = 2 
Output: (19, 23) 

Using min() with Lambda

This method directly computes the differences and returns the minimum in a single line. It is the most concise and efficient method to find the tuple whose Kth element is closest to the target.

Python
t = [(3, 4, 9), (5, 6, 7)]
tup = (1, 2, 5)
K =3
res = min(t, key=lambda x: abs(x[K-1] - tup[K-1]))
print(res)

Output
(5, 6, 7)

Explanation: min(..., key=lambda x: abs(x[K-1] - tup[K-1])) computes the absolute difference for each tuple and returns the one with the smallest difference.

Using enumerate() + Loop

This method explicitly iterates through the tuples, tracking the smallest difference and its index. It is easy to understand and useful when you also need the position of the closest tuple.

Python
t = [(3, 4, 9), (5, 6, 7)]
tup = (1, 2, 5)
K = 3

min_diff, res = float('inf'), None
for idx, val in enumerate(t):
    diff = abs(val[K-1] - tup[K-1])
    if diff < min_diff:
        min_diff, res = diff, idx

print(t[res])

Output
(5, 6, 7)

Explanation:

  • min_diff, res = float('inf'), None: initializes tracking of the smallest difference (min_diff) and the corresponding index (res).
  • if diff < min_diff: min_diff, res = diff, idx: updates the smallest difference and its index whenever a smaller difference is found.

Using heapq.nsmallest()

This method uses a heap to efficiently find the tuple(s) with the smallest difference. It’s especially useful when you want the closest N tuples rather than just one.

Python
import heapq

t = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]
tup = (17, 23)
K = 2
res = heapq.nsmallest(1, t, key=lambda x: abs(x[K-1] - tup[K-1]))[0]
print(res)

Output
(19, 23)

Explanation:

  • heapq.nsmallest(1, ...): finds the smallest element(s) based on the provided key.
  • key=lambda x: abs(x[K-1] - tup[K-1]): computes the difference.
  • [0]: extracts the closest tuple.

Using sorted() with Custom Key

This method sorts all tuples based on the absolute difference from the target tuple’s Kth element and then selects the first tuple as the closest.

Python
t = [(3, 4, 9), (5, 6, 7)]
tup = (1, 2, 5)
K = 3
s = sorted(t, key=lambda x: abs(x[K-1] - tup[K-1]))
res = s[0]
print(res)

Output
(5, 6, 7)

Explanation:

  • sorted(t, key=lambda x: abs(x[K-1] - tup[K-1])): sorts the tuples in t based on the absolute difference between their Kth element and tup[K-1].
  • s[0]: picks the first tuple, which has the smallest difference.

Explore