- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Closest Pair to Kth index element in Tuple using Python
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 −
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])
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)
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.
- Python – Extract Kth element of every Nth tuple in List
- Closest Pair of Points Problem
- Kth Column Product in Tuple List in Python
- Convert tuple to adjacent pair dictionary in Python
- Python – Find Kth Even Element
- Create Pair Tuple using with() method in Java
- Get minimum difference in Tuple pair in Python
- Create Pair Tuple in Java
- How to create 2-tuple or pair tuple in C#?
- Kth Largest Element in an Array in Python
- Kth Smallest Element in a BST in Python
- Kth Largest Element in a Stream in Python
- Python Program for Find the closest pair from two sorted arrays
- Iterate through Java Pair Tuple