
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 −
Example
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.
Advertisements