Python Closest Pair to Kth index element in Tuple (original) (raw)

Last Updated : 12 Nov, 2025

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)

`

**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])

`

**Explanation:

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)

`

**Explanation:

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)

`

**Explanation: